I made canvas that you can draw on it, but when I resize website to mobile size it doesn't work. My code only works on mouse. Is there any way to make it also work on mobile devices. Here's my code:
const points = [];
const mouse = { x: 0, y: 0, button: false }
const ctx = canvas.getContext("2d");
canvas.addEventListener("mousemove", mouseEvents);
canvas.addEventListener("mousedown", mouseEvents);
canvas.addEventListener("mouseup", mouseEvents);
var x = "black",
y = 2;
function mouseEvents(e) {
mouse.x = e.pageX - 1;
mouse.y = e.pageY - 1;
const lb = mouse.button;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
if (mouse.button) {
if (!lb) { points.length = 0 }
points.push({ x: mouse.x, y: mouse.y });
drawPoints();
}
}
function drawPoints() {
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
if (mode == "pen") {
ctx.globalCompositeOperation = "source-over";
for (const p of points) { ctx.lineTo(p.x, p.y); }
ctx.stroke();
} else {
ctx.globalCompositeOperation = "destination-out";
ctx.arc(mouse.x, mouse.y, 8, 0, Math.PI * 2, false);
ctx.stroke();
ctx.fill();
}
}
Replace "mousemove" by "pointermove" and so on to cover both mouse and touch input. For the event mentioned above, you might have to call e.StopPropagation() additionally to prevent page scrolling on mobile devices.