簡體   English   中英

在畫布上繪圖不適用於傳感器(手機)HTML/JavaScript

[英]Drawing on canvas not working on sensors(phones) 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()以防止在移動設備上滾動頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM