Reputation: 323
I have this simple code for drawing with mouse in canvas. But if I try to style the canvas, like altering the width or centering, the pointer and line drawn get separated. How do I solve this?
JavaScript:
var el = document.getElementById('canvas');
var ctx = el.getContext('2d');
var isDrawing;
el.onmousedown = function(e) {
isDrawing = true;
ctx.moveTo(e.clientX, e.clientY);
};
el.onmousemove = function(e) {
if (isDrawing) {
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
}
};
el.onmouseup = function() {
isDrawing = false;
};
HTML:
CSS:
canvas {
border: 2px solid #ccc;
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 800px;
}
Here's a Fiddle
Upvotes: 0
Views: 46
Reputation: 32859
NEVER set canvas's width / height using css. It's really a bad idea. Always use the native width / height property of the canvas.
Also, you should probably be using e.offsetX
and e.offsetY
to get the x and y coordinates of the mouse.
Here's a working fiddle
Upvotes: 1