要在Vue 3中实现手动签名的功能,可以结合Vue的模板和生命周期钩子函数来实现。下面是一个简单的示例代码:
<template>
<div>
<h1>手动签名</h1>
<canvas ref="signatureCanvas" width="500" height="200" style="border:1px solid #000000;"></canvas>
<br>
<button @click="clearCanvas">清除</button>
<button @click="saveSignature">保存</button>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0,
};
},
mounted() {
this.canvas = this.$refs.signatureCanvas;
this.context = this.canvas.getContext("2d");
this.canvas.addEventListener("mousedown", this.startDrawing);
this.canvas.addEventListener("mousemove", this.draw);
this.canvas.addEventListener("mouseup", this.stopDrawing);
this.canvas.addEventListener("mouseleave", this.stopDrawing);
},
methods: {
startDrawing(e) {
this.isDrawing = true;
this.lastX = e.offsetX;
this.lastY = e.offsetY;
},
draw(e) {
if (!this.isDrawing) return;
this.context.beginPath();
this.context.moveTo(this.lastX, this.lastY);
this.context.lineTo(e.offsetX, e.offsetY);
this.context.strokeStyle = "#000000";
this.context.lineWidth = 2;
this.context.stroke();
this.lastX = e.offsetX;
this.lastY = e.offsetY;
},
stopDrawing() {
this.isDrawing = false;
},
clearCanvas() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
saveSignature() {
const imageURL = this.canvas.toDataURL();
// 在此处可以将imageURL发送到服务器保存,或进行其他处理
console.log(imageURL);
},
},
};
</script>
这段代码是一个Vue组件,模板中包含了一个<canvas>元素用于绘制签名。通过ref属性,我们可以获取到对应的canvas元素,并在对应的生命周期钩子函数中注册事件监听器。绘制签名时,在mousedown、mousemove和mouseup事件中调用对应的方法来绘制路径、更新画笔坐标和状态。清除按钮调用clearCanvas方法来清除canvas内容,保存按钮调用saveSignature方法将canvas的内容转为base64编码的图像URL并打印到控制台。
你可以根据需要修改saveSignature方法,以便将签名图像发送到服务器保存或进行其他处理。
网友评论