Reputation: 318
I am making a project where i want to draw on a canvas. I get the draw method on mouseover and intend to draw a line while following the mouse. It draws the line perfectly only not on the correct position.
It is made possibly bij JQuery.
var canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
ctx.beginPath();
$("#myCanvas").mousemove(function(arg)
{ ctx.lineTo(arg.pageX,arg.pageY-80);
ctx.stroke();
});
My html Canvas code:
<canvas id="myCanvas" width="500" height="500">
</canvas>
I hope it is understandable and that somebody can help me. (information the -80 at pageY is because i works better on my screen than)
Upvotes: 0
Views: 1242
Reputation:
Here is an optional way of reading mouse position relative to canvas:
$("#myCanvas").mousemove(function(arg) {
var pos = getMousePos(canvas, arg);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
});
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect(); // absolute position of canvas
return {
x: e.clientX - rect.left, // make x/y relative to canvas
y: e.clientY - rect.top
};
}
Just a side note: We will get issues with that lineTo/stroke combo BTW as the lineTo will add to path and when you stroke, the new line as well as all the other lines added will be stroked. As it is it will become slower the more lines that are drawn and anti-aliased pixels will start to appear. You can use beginPath and moveTo to solve but that is out-of-scope for this question.
Upvotes: 1