画布触摸事件js

时间:2021-03-05 11:55:45

标签: javascript html

我正在尝试让一个 html 画布在触摸设备上签名,它适用于鼠标事件,我一直在寻找其他答案,但我无法理解。

        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        canvas.width = 300;
        canvas.height = 95;
        ctx.lineJoin = "round";
        ctx.lineCap = "round";

        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;
        // Set up touch events for desktop, etc
        function draw(e) {
          if (!isDrawing) return;
          ctx.beginPath();
          ctx.moveTo(lastX, lastY);
          ctx.lineTo(e.offsetX, e.offsetY);
          ctx.stroke();
          [lastX, lastY] = [e.offsetX, e.offsetY];
        }

        canvas.addEventListener("mousedown", (e) => {
          isDrawing = true;
          [lastX, lastY] = [e.offsetX, e.offsetY];
        });
        canvas.addEventListener("mousemove", draw);
        canvas.addEventListener("mouseup", () => isDrawing = false);
        canvas.addEventListener("mouseout", () => isDrawing = false);
        // Set up touch events for mobile, etc
        function drawTouch(e) {
          if (!isDrawing) return;
          ctx.beginPath();
          ctx.moveTo(lastX, lastY);
          ctx.lineTo(e.touches[0].clientX, e.touches[0].clientY);
          ctx.stroke();
          [lastX, lastY] = [e.touches[0].clientX, e.touches[0].clientY];
        }
        canvas.addEventListener("ontouchstart", (e) => {
          isDrawing = true;
          [lastX, lastY] = [e.touches[0].clientX, e.touches[0].clientY];
        });
        canvas.addEventListener("touchmove", drawTouch);
        canvas.addEventListener("touchend", () => isDrawing = false);
        canvas.addEventListener("touchcancel", () => isDrawing = false);

      }

感谢您的时间 格雷厄姆

0 个答案:

没有答案