vue手写签名如何实现
实现手写签名的基本思路
在Vue中实现手写签名功能,通常需要借助HTML5的Canvas API来捕获用户的绘制操作。核心流程包括初始化画布、监听触摸/鼠标事件、记录轨迹以及生成签名图片。
安装依赖(可选)
对于需要快速实现的场景,可以使用现成的库如vue-signature-pad:
npm install vue-signature-pad
基于Canvas的原生实现
初始化画布
在Vue组件的<template>中定义Canvas元素:
<canvas
ref="signaturePad"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@touchstart="startDrawing"
@touchmove="draw"
@touchend="stopDrawing"
></canvas>
核心逻辑代码
export default {
data() {
return {
isDrawing: false,
ctx: null
}
},
mounted() {
this.initCanvas();
},
methods: {
initCanvas() {
const canvas = this.$refs.signaturePad;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
this.ctx = canvas.getContext('2d');
this.ctx.strokeStyle = '#000';
this.ctx.lineWidth = 2;
},
startDrawing(e) {
this.isDrawing = true;
const pos = this.getPosition(e);
this.ctx.beginPath();
this.ctx.moveTo(pos.x, pos.y);
},
draw(e) {
if (!this.isDrawing) return;
const pos = this.getPosition(e);
this.ctx.lineTo(pos.x, pos.y);
this.ctx.stroke();
},
stopDrawing() {
this.isDrawing = false;
},
getPosition(e) {
const rect = e.target.getBoundingClientRect();
return {
x: (e.clientX || e.touches[0].clientX) - rect.left,
y: (e.clientY || e.touches[0].clientY) - rect.top
};
},
clearSignature() {
this.ctx.clearRect(0, 0,
this.$refs.signaturePad.width,
this.$refs.signaturePad.height
);
},
saveSignature() {
return this.$refs.signaturePad.toDataURL('image/png');
}
}
}
使用第三方库(vue-signature-pad示例)
import VueSignaturePad from 'vue-signature-pad';
export default {
components: { VueSignaturePad },
methods: {
save() {
const { data } = this.$refs.signaturePad.save();
console.log(data); // 获取Base64格式签名
},
clear() {
this.$refs.signaturePad.clear();
}
}
}
对应模板:
<vue-signature-pad ref="signaturePad" />
<button @click="save">保存</button>
<button @click="clear">清除</button>
样式优化建议
canvas {
border: 1px solid #ddd;
background-color: #f8f8f8;
touch-action: none; /* 防止移动端页面滚动 */
}
注意事项
- 移动端需同时处理
touch和mouse事件 - 考虑添加防抖处理高频绘制事件
- 保存时可选择PNG或JPEG格式,PNG支持透明背景
- 高DPI屏幕需通过CSS设置画布实际显示尺寸,再通过JavaScript调整
width/height属性进行缩放







