vue实现手写签批
实现手写签批功能
在Vue中实现手写签批功能,可以通过HTML5的Canvas API结合触摸事件或鼠标事件来完成。以下是具体的实现方法:
引入Canvas元素
在Vue组件的模板中添加一个Canvas元素,用于绘制手写内容:
<template>
<div>
<canvas
ref="signatureCanvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@touchstart="startDrawing"
@touchmove="draw"
@touchend="stopDrawing"
></canvas>
<button @click="clearCanvas">清除</button>
<button @click="saveSignature">保存</button>
</div>
</template>
初始化Canvas
在组件的mounted生命周期钩子中初始化Canvas,设置其大小和样式:
mounted() {
const canvas = this.$refs.signatureCanvas;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
this.ctx = canvas.getContext('2d');
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 2;
}
实现绘图功能
添加绘图相关的方法,处理鼠标和触摸事件:
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0,
ctx: null
};
},
methods: {
startDrawing(e) {
this.isDrawing = true;
const canvas = this.$refs.signatureCanvas;
const rect = canvas.getBoundingClientRect();
this.lastX = (e.clientX || e.touches[0].clientX) - rect.left;
this.lastY = (e.clientY || e.touches[0].clientY) - rect.top;
},
draw(e) {
if (!this.isDrawing) return;
const canvas = this.$refs.signatureCanvas;
const rect = canvas.getBoundingClientRect();
const currentX = (e.clientX || e.touches[0].clientX) - rect.left;
const currentY = (e.clientY || e.touches[0].clientY) - rect.top;
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(currentX, currentY);
this.ctx.stroke();
this.lastX = currentX;
this.lastY = currentY;
},
stopDrawing() {
this.isDrawing = false;
}
}
清除和保存功能
添加清除Canvas和保存签名的方法:
methods: {
clearCanvas() {
const canvas = this.$refs.signatureCanvas;
this.ctx.clearRect(0, 0, canvas.width, canvas.height);
},
saveSignature() {
const canvas = this.$refs.signatureCanvas;
const image = canvas.toDataURL('image/png');
// 可以发送到服务器或本地保存
console.log(image);
}
}
样式调整
为Canvas添加一些基本样式,确保其在页面上正确显示:
canvas {
border: 1px solid #000;
background-color: #fff;
width: 100%;
height: 200px;
}
button {
margin-top: 10px;
padding: 5px 10px;
}
响应式处理
如果需要支持移动端触摸事件,确保Canvas的触摸事件不会被浏览器默认行为阻止:
methods: {
startDrawing(e) {
e.preventDefault();
this.isDrawing = true;
// 其余代码...
},
draw(e) {
e.preventDefault();
// 其余代码...
}
}
使用第三方库
如果不想从头开始实现,可以使用现成的Vue手写签名库,如vue-signature-pad:
npm install vue-signature-pad
在组件中使用:
import VueSignaturePad from 'vue-signature-pad';
export default {
components: {
VueSignaturePad
},
methods: {
save() {
const { data } = this.$refs.signature.save();
console.log(data);
},
undo() {
this.$refs.signature.undo();
}
}
}
<template>
<vue-signature-pad ref="signature" />
<button @click="save">保存</button>
<button @click="undo">撤销</button>
</template>
注意事项
确保Canvas的大小在初始化时正确设置,避免绘制时出现偏移。对于移动端,需要处理触摸事件并阻止默认行为,以确保绘图流畅。保存的签名可以转换为Base64格式的图片,便于上传到服务器或本地存储。







