When I make the HTML canvas bigger, the point I click and the point I draw is very far away. When instead the canvas is of standard size it is perfect. How can I fix it? I've tried to do it in CSS with width of 100vw; but nothing. I also tried to define it in the HTML but in any case also there the stroke is wrong with respect to the position of the mouse.
@import "compass/css3";
html, body {
width: 100%;
height: 100%;
margin: 0px;
overflow: hidden;
&:hover {
span {
display: none;
}
}
}
canvas {
cursor: crosshair;
border: 1px solid red;
width: 100vw;
height: 100vh;
}
span {
font-family: 'Georgia', cursive;
font-size: 40px;
position: fixed;
top: 50%;
left: 50%;
color: #000;
margin-top: -40px;
margin-left: -200px;
}
<canvas id='canvas'></canvas>
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.clientX, e.clientY];
});
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
The issue is that you are using e.clientX and e.clientY for the mouse position when you start drawing. clientX and clientY are relative to the viewport (browser window), so when you increase the canvas size, the mouse position becomes incorrect. To fix this, you need to use e.offsetX and e.offsetY instead. These values are relative to the canvas, so they will always be accurate, regardless of canvas size. So your code should look like this:
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});