vue实现签章
Vue 实现签章功能
在 Vue 中实现签章功能通常需要借助第三方库或自定义画布操作。以下是两种常见实现方式:
使用 HTML5 Canvas 实现基础签章
<template>
<div>
<canvas ref="signatureCanvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"></canvas>
<button @click="clearCanvas">清除</button>
<button @click="saveSignature">保存</button>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0
}
},
methods: {
startDrawing(e) {
this.isDrawing = true;
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
},
draw(e) {
if (!this.isDrawing) return;
const canvas = this.$refs.signatureCanvas;
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(this.lastX, this.lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
},
stopDrawing() {
this.isDrawing = false;
},
clearCanvas() {
const canvas = this.$refs.signatureCanvas;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
saveSignature() {
const canvas = this.$refs.signatureCanvas;
const image = canvas.toDataURL('image/png');
console.log(image); // 可上传到服务器或保存
}
},
mounted() {
const canvas = this.$refs.signatureCanvas;
canvas.width = 400;
canvas.height = 200;
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.lineCap = 'round';
}
}
</script>
使用第三方库 vue-signature-pad
-
安装依赖:
npm install vue-signature-pad -
组件实现:
<template> <div> <VueSignaturePad ref="signaturePad" width="400px" height="200px" :options="{ penColor: '#000' }" /> <button @click="undo">撤销</button> <button @click="clear">清除</button> <button @click="save">保存</button> </div> </template>
export default { components: { VueSignaturePad }, methods: { undo() { this.$refs.signaturePad.undoSignature(); }, clear() { this.$refs.signaturePad.clearSignature(); }, save() { const { data } = this.$refs.signaturePad.saveSignature(); console.log(data); // base64格式图像数据 } } }
```实现印章效果
如需实现圆形印章效果,可添加以下CSS样式:
.canvas-container {
border: 1px dashed #ccc;
border-radius: 50%;
width: 200px;
height: 200px;
overflow: hidden;
}
注意事项
- 移动端需添加触摸事件支持(@touchstart, @touchmove, @touchend)
- 保存时可转换为PNG或JPG格式
- 考虑添加时间戳等防伪信息
- 重要签章建议结合后端验证机制
以上方法可根据实际需求选择使用,第三方库提供更多高级功能如撤销、重做等,而原生Canvas实现则更灵活可控。







