能实现手写签名的h5组件示例代码
时间: 2024-02-06 07:03:06 浏览: 151
html5 canvas实现手写签名
5星 · 资源好评率100%
以下是一个简单的手写签名H5组件的示例代码:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>手写签名</title>
</head>
<body>
<canvas id="signatureCanvas" width="400" height="200"></canvas>
<button id="clearButton">清空</button>
<button id="saveButton">保存</button>
<img id="signatureImg" src="" style="display:none;">
<script src="signature.js"></script>
</body>
</html>
```
JS代码:
```javascript
// 获取canvas元素和上下文
var canvas = document.getElementById("signatureCanvas");
var context = canvas.getContext("2d");
// 设置画笔样式
context.strokeStyle = "#000000";
context.lineWidth = 2;
// 设置标记变量
var isDrawing = false;
var lastX = 0;
var lastY = 0;
// 监听鼠标事件
canvas.addEventListener("mousedown", startDrawing);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", endDrawing);
canvas.addEventListener("mouseout", endDrawing);
// 清空画布
var clearButton = document.getElementById("clearButton");
clearButton.addEventListener("click", function() {
context.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById("signatureImg").src = "";
});
// 保存签名
var saveButton = document.getElementById("saveButton");
saveButton.addEventListener("click", function() {
var dataURL = canvas.toDataURL();
document.getElementById("signatureImg").src = dataURL;
alert("签名已保存!");
});
// 开始绘制
function startDrawing(event) {
isDrawing = true;
lastX = event.clientX - canvas.offsetLeft + window.pageXOffset;
lastY = event.clientY - canvas.offsetTop + window.pageYOffset;
}
// 绘制
function draw(event) {
if (isDrawing) {
var currentX = event.clientX - canvas.offsetLeft + window.pageXOffset;
var currentY = event.clientY - canvas.offsetTop + window.pageYOffset;
context.beginPath();
context.moveTo(lastX, lastY);
context.lineTo(currentX, currentY);
context.stroke();
lastX = currentX;
lastY = currentY;
}
}
// 结束绘制
function endDrawing(event) {
isDrawing = false;
}
```
这个示例代码中,我们创建了一个canvas元素,并监听了鼠标事件,根据鼠标位置在canvas上绘制签名。然后我们还创建了两个按钮,一个用于清空画布,一个用于保存签名。当保存签名时,我们将canvas转换为base64编码的图片,并将其显示在img元素中。
阅读全文