<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="signatureCanvas" style="border:1px solid #ccc;"></canvas>
<button id="saveButton">保存签名</button>
<script>
const canvas = document.getElementById('signatureCanvas');
const saveButton = document.getElementById('saveButton');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
// 设置 Canvas 的宽高
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function startDrawing(e) {
isDrawing = true;
// 根据设备类型获取坐标
const coordinates = getCoordinates(e);
[lastX, lastY] = coordinates;
}
function draw(e) {
if (!isDrawing) return;
// 根据设备类型获取坐标
const coordinates = getCoordinates(e);
const [clientX, clientY] = coordinates;
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(clientX, clientY);
ctx.stroke();
[lastX, lastY] = coordinates;
}
function stopDrawing() {
isDrawing = false;
}
function saveSignature() {
const signatureData = canvas.toDataURL();
console.log(signatureData);
}
function getCoordinates(e) {
let clientX, clientY;
// 检测设备类型
if (e.touches) {
// 触摸设备,取第一个触摸点的坐标
clientX = e.touches[0].clientX;
clientY = e.touches[0].clientY;
} else {
// 鼠标事件
clientX = e.clientX;
clientY = e.clientY;
}
return [clientX, clientY];
}
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', stopDrawing);
saveButton.addEventListener('click', saveSignature);
</script>
</body>
</html>
canvas电子签(pc+mobile)
最新推荐文章于 2024-07-19 15:13:24 发布