I’m creating a drawing application with HTML5 canvas. It works accept for one thing. The drawing happens like ~50px down/right from the cursor. Below is my code, is it possible to tell why this is happening?
var letsdraw = false;
var theCanvas = document.getElementById('paint');
var ctx = theCanvas.getContext('2d');
theCanvas.width = 420;
theCanvas.height = 300;
$('#paint').mousemove(function(e) {
if (letsdraw === true){
ctx.strokeStyle = 'blue';
ctx.lineWidth = 100;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(e.pageX, e.pageY);
ctx.lineTo(e.pageX, e.pageY);
ctx.stroke();
}
});
$('#paint').mousedown(function(){
letsdraw = true;
});
$('#paint').mouseup(function(){
letsdraw = false;
});
A couple of items I see. First, for your core problem, you’re only looking at pageX and pageY, but you’re not taking in to account the offset of the canvas. So, if the canvas is 50 px down on the page, you’re going to be drawing in the wrong location.
Also, you won’t want to use moveTo and lineTo both in the mousemove, as this isn’t valid syntax. You’re basically saying “draw a line from point (x,y) to (x,y). Here’s an updated bit of code for you, you can find the jsfiddle for it here: http://jsfiddle.net/fordlover49/wPx4d/