直接复制粘贴
代码如下
<!DOCTYPE html>
<html>
<head><title>Signature Pad</title><style>canvas {border: 1px solid #ccc;}</style>
</head>
<body><canvas id="signature-pad" width="400" height="200"></canvas><br><button id="*****-button">Clear</button><script>// 获取canvas元素var canvas = document.getElementById('signature-pad');// 获取2D绘图上下文var ctx = canvas.getContext('2d');// 定义变量记录鼠标是否按下var isMouseDown = false;// 定义变量记录鼠标位置var lastX, lastY;// 绑定鼠标按下事件canvas.addEventListener('mousedown', function(e) {isMouseDown = true;// 记录鼠标位置lastX = e.clientX - canvas.offsetLeft;lastY = e.clientY - canvas.offsetTop;});// 绑定鼠标移动事件canvas.addEventListener('mousemove', function(e) {if (isMouseDown) {// 计算鼠标移动距离var currentX = e.clientX - canvas.offsetLeft;var currentY = e.clientY - canvas.offsetTop;// 绘制线条ctx.beginPath();ctx.moveTo(lastX, lastY);ctx.lineTo(currentX, currentY);ctx.stroke();// 更新鼠标位置lastX = currentX;lastY = currentY;}});// 绑定鼠标松开事件canvas.addEventListener('mouseup', function(e) {isMouseDown = false;});// 绑定清空按钮点击事件var Button = document.getElementById('*****-button');Button.addEventListener('click', function() {// 清空画布ctx.clearRect(0, 0, canvas.width, canvas.height);});</script>
</body>
</html>