JavaScript实现手写签名,可触屏手写,支持移动端与PC端双端保存
实现手写签名功能,可以使用HTML5的<canvas>
元素。以下是一个简单的示例,展示了如何在网页上实现手写签名,并支持在移动端和桌面端上使用。
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signature Pad</title>
<style>
canvas {
border: 1px solid #000;
touch-action: none;
}
</style>
</head>
<body>
<canvas id="signature-pad" width="300" height="150"></canvas>
<script src="signature.js"></script>
</body>
</html>
JavaScript部分 (signature.js
):
const canvas = document.getElementById('signature-pad');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
const resizeCanvas = () => {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
};
const 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];
};
const startDrawing = (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
};
const stopDrawing = () => {
isDrawing = false;
};
// Event listeners
canvas.addEventListener('mousedown', (e) => {
e.preventDefault();
startDrawing(e);
draw(e);
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseleave', stopDrawing);
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
startDrawing(e.touches[0]);
draw(e.touches[0]);
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
draw(e.touches[0]);
});
canvas.addEventListener('touchend', stopDrawing);
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
这段代码提供了基本的手写签名功能,并且支持鼠标和触摸屏操作。在移动端上,你可能需要额外处理触摸事件,以确保签名的流畅性和清晰度。此外,你可以添加清除签名的功能,以及将签名转换为图像等额外的功能。
评论已关闭