javascript - 画布触摸事件js
问题描述
我试图让一个 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);
}
谢谢你的时间格雷厄姆
解决方案
推荐阅读
- sql - 提供表中特定列的“喜欢”函数的值?
- amazon-cognito - 如何在 AWS cognito 中更改属性之前要求验证码
- wordpress - cpt中按日期格式自定义字段排序
- android - Android 应用内更新 api 无法在 Android TV 设备上运行
- ios - 如何避免将 uicollectionview 作为部分加载
- c# - 如何使用 C# Windows 应用程序在 3rd 方桌面应用程序中发送密钥库
- r - 在小标题中添加两列并将总和保存到第三列正在使第三列成为数据框
- angular - Angular - 将两个属性绑定到一个输入字段并将其他属性作为验证参数传递
- c++ - 为什么要使用引用来获取 *char?当我们使用指针时不使用引用不是更好吗?
- java - Java 中的 FileDescriptor 类