I wrote this code to draw free lines like paint,
const canvas = document.getElementById("canv");
let mousedown = false;
const ctx = canvas.getContext("2d");
ctx.lineWidth = 5;
let x;
let y;
window.addEventListener("mousedown", (event) => {
console.log('clicked');
if (event.which == 3) {
mousedown = false;
} else if (event.which == 1) {
mousedown = true;
}
window.addEventListener('contextmenu', (event) => {
event.preventDefault();
})
window.addEventListener("mousemove", (event) => {
if (mousedown) {
document.body.style.cursor = "crosshair";
console.log("MOVING");
ctx.beginPath();
x = event.clientX - 100;
y = event.clientY - 100;
ctx.moveTo(x, y);
ctx.arc(x, y, 2, 0, 2 * Math.PI, false);
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.closePath();
} else if (!mousedown) {
document.body.style.cursor = "crosshair";
console.log("MOVING");
ctx.beginPath();
x = event.clientX - 100;
y = event.clientY - 100;
ctx.moveTo(x, y);
ctx.arc(x, y, 0.5, 0, 2 * Math.PI, true);
ctx.strokeStyle = 'white';
ctx.stroke();
ctx.closePath();
}
})
})
canvas {
position: absolute;
top: 100px;
left: 100px;
border: 1px solid;
}
<canvas id="canv" width="700" height="700" ">
Your Browser Doesn't Support Canvas.
</canvas>
The code is working, but I can only draw with certain speed, otherwise the line becomes distributed circles, is there any property or function to fix this issue?