Draws nothing if the item is biased.
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;
}
How to fix it? Thanks in advance.
The coordinates on the canvas, and cooridnates of clientX and clientY have different origins. This version realigns them:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With