画布上不工作的传感器(手机)HTML/JavaScript



我做了画布,你可以在上面画画,但是当我把网站大小调整到手机大小时,它不起作用。我的代码只适用于鼠标。有没有办法让它在移动设备上也能运行?下面是我的代码:

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();
    }
}

"mousemove"替换为"pointermove",以此类推,以覆盖鼠标和触摸输入。对于上面提到的事件,你可能需要额外调用e.StopPropagation()来防止移动设备上的页面滚动。

最新更新