when I draw on my canvas, the line doesn't follow the cursor, the line is at another point away from the cursor. for example, if I draw at point A, the cursor will stay at point A but the line I draw can be at point b.
I think this is happening because I want to make the canvas area (drawing area) larger, because if the canvas is the default size this won't happen
const paintCanvas = document.querySelector('.js-paint');
const context = paintCanvas.getContext('2d');
context.lineCap = 'round';
const colorPicker = document.querySelector('.js-color-picker');
const clearButton = document.querySelector('.js-clear-canvas');
clearButton.addEventListener('click', () => {
context.clearRect(0, 0, paintCanvas.width, paintCanvas.height);
});
colorPicker.addEventListener('change', event => {
context.strokeStyle = event.target.value;
});
const lineWidthRange = document.querySelector('.js-line-range');
const lineWidthLabel = document.querySelector('.js-range-value');
lineWidthRange.addEventListener('input', event => {
const width = event.target.value;
lineWidthLabel.innerHTML = width;
context.lineWidth = width;
});
let x = 0, y = 0;
let isMouseDown = false;
const stopDrawing = () => { isMouseDown = false; }
const startDrawing = event => {
isMouseDown = true;
[x, y] = [event.offsetX, event.offsetY];
}
const drawLine = event => {
if (isMouseDown) {
const newX = event.offsetX;
const newY = event.offsetY;
context.beginPath();
context.moveTo(x, y);
context.lineTo(newX, newY);
context.stroke();
//[x, y] = [newX, newY];
x = newX;
y = newY;
}
}
paintCanvas.addEventListener('mousedown', startDrawing);
paintCanvas.addEventListener('mousemove', drawLine);
paintCanvas.addEventListener('mouseup', stopDrawing);
paintCanvas.addEventListener('mouseout', stopDrawing);
.canvas {
background-color: white;
margin-top: 50px;
margin-left: 25px;
width: 100vh;
height: 70vh;
border-radius: 20px;
border: 10px #208cff solid;
box-shadow: 0px 0px 15px inset grey, 0px 0px 15px #0263ca;
}
.canvas .paint-canvas {
display: block;
width: 100vh;
height: 70vh;
}
.canvas .paint-canvas:hover {
cursor: crosshair;
}
.canvas .top {
display: inline;
}
<!-- Canvas -->
<div class="canvas">
<h1>Scratch Here</h1>
<input type="color" class="js-color-picker color-picker">
<div class="top">
<input type="range" class="js-line-range" min="1" max="72" value="1">
<label class="js-range-value">1</label>Px
</div>
<canvas class="js-paint paint-canvas" width="600" height="300"></canvas>
<button class="js-clear-canvas">Clear Canvas</button>
</div>