带偏移的画布元素

owl*_*owl 4 html javascript css canvas

如果项目有偏差,则不会绘制任何内容。

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();
});
Run Code Online (Sandbox Code Playgroud)

CSS:

#drawing {
    border: 1px solid #000;
    position: absolute;
    top: 50px;
    right: 0;
}
#without_offset {
    border: 1px solid #000;
}
Run Code Online (Sandbox Code Playgroud)

如何修复它?提前致谢。

sab*_*bof 5

画布上的坐标以及 和 的坐标clientX具有clientY不同的原点。这个版本重新调整了它们:

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")
));
Run Code Online (Sandbox Code Playgroud)

现场演示