手机上的效果图
需要注意,手机触摸和鼠标不是一个事件,不能通用,上一篇是关于使用鼠标的样例
相关代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.buttons {margin-top: 10px;}</style>
</head><body><div><canvas id="signatureCanvas" width="500" height="200" style="border:solid;"></canvas><button onclick="clearSignature()">清除</button><button onclick="undoLast()">清除上一步</button><button onclick="saveSignature()">保存</button></div><script>const canvas = document.getElementById('signatureCanvas');const ctx = canvas.getContext('2d');let isDrawing = false;let lastX, lastY;let strokes = []; // 用于存储每一步的绘制操作// 触摸开始事件function handleTouchStart(e) {e.preventDefault(); // 阻止默认的触摸事件isDrawing = true;[lastX, lastY] = [e.touches[0].clientX - canvas.offsetLeft, e.touches[0].clientY - canvas.offsetTop];strokes.push([]); // 开始新的笔画}// 触摸移动事件function handleTouchMove(e) {e.preventDefault(); // 阻止默认的触摸事件if (!isDrawing) return; // 如果没有触摸,则退出函数const x = e.touches[0].clientX - canvas.offsetLeft;const y = e.touches[0].clientY - canvas.offsetTop;ctx.beginPath();ctx.moveTo(lastX, lastY);ctx.lineTo(x, y);ctx.stroke();strokes[strokes.length - 1].push({ x: lastX, y: lastY, x2: x, y2: y }); // 记录当前笔画[lastX, lastY] = [x, y];}// 触摸结束事件function handleTouchEnd(e) {e.preventDefault(); // 阻止默认的触摸事件isDrawing = false;}// 清除签名function clearSignature() {ctx.clearRect(0, 0, canvas.width, canvas.height);strokes = []; // 清空所有笔画记录}// 撤销上一步function undoLast() {strokes.pop(); // 移除最后一个笔画redraw(); // 重新绘制画布}// 重新绘制画布function redraw() {ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布strokes.forEach(stroke => {stroke.forEach(line => {ctx.beginPath();ctx.moveTo(line.x, line.y);ctx.lineTo(line.x2, line.y2);ctx.stroke();});});}// 保存签名function saveSignature() {const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);// 将图片数据转换成 base64 格式const base64ImageData = canvas.toDataURL();console.log(base64ImageData);}// 绑定事件canvas.addEventListener('touchstart', handleTouchStart);canvas.addEventListener('touchmove', handleTouchMove);canvas.addEventListener('touchend', handleTouchEnd);canvas.addEventListener('touchcancel', handleTouchEnd);</script>
</body></html>