gpt4 book ai didi

javascript - 具有偏移量的 Canvas 元素

转载 作者:行者123 更新时间:2023-11-30 08:44:44 26 4
gpt4 key购买 nike

如果元素有偏差,则不绘制任何内容。

jsfiddle:http://jsfiddle.net/9UyxF/

JavaScript:

var ctx = document.getElementById("drawing").getContext("2d");

$("#drawing").mousemove(function(e) {
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
});

var ctx_without_offset = document.getElementById("without_offset").getContext("2d");

$("#without_offset").mousemove(function(e) {
ctx_without_offset.lineTo(e.clientX, e.clientY);
ctx_without_offset.stroke();
});

CSS:

#drawing {
border: 1px solid #000;
position: absolute;
top: 50px;
right: 0;
}
#without_offset {
border: 1px solid #000;
}

如何解决?提前致谢。

最佳答案

Canvas 上的坐标与clientXclientY 的坐标有不同的来源。此版本重新排列它们:

function makeDrawFunction(elem) {
var context = elem.getContext('2d');
return function(e) {
var offset = $(elem).offset();
context.lineTo(e.clientX - offset.left, e.clientY - offset.top);
context.stroke();
}
}


$("#drawing").mousemove(makeDrawFunction(
document.getElementById("drawing")
));

$("#without_offset").mousemove(makeDrawFunction(
document.getElementById("without_offset")
));

live demo

关于javascript - 具有偏移量的 Canvas 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22990755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com