im trying to make it so when someone draws on the canvas tag it is synced with the mouse. but the drawing always appears to the bottom right of the mouse. below is the all the code for the canvas tag i made.
// Set the initial canvas dimensions
const initialWidth = 400;
const initialHeight = 400;
canvas.width = initialWidth;
canvas.height = initialHeight;
// Resize the canvas to new dimensions
function resizeCanvas(newWidth, newHeight) {
canvas.width = newWidth;
canvas.height = newHeight;
}
// Call the resizeCanvas function with new dimensions
resizeCanvas(newWidth, newHeight);
// Get mouse position relative to the canvas
function getMousePos(canvas, event) {
const rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
// Start drawing when the mouse is pressed
function startDrawing(e) {
isDrawing = true;
const pos = getMousePos(canvas, e);
[lastX, lastY] = [pos.x, pos.y];
}
// Draw a line following the mouse movement
function draw(e) {
if (!isDrawing) return;
const pos = getMousePos(canvas, e);
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
[lastX, lastY] = [pos.x, pos.y];
}
// Stop drawing when the mouse is released or leaves the canvas
function stopDrawing() {
isDrawing = false;
}
ive tried different solutions ive found online but none seem to work