vue实现手势签到
Vue 实现手势签到的步骤
使用 vue-signature 插件
安装 vue-signature 插件,这是一个专门用于 Vue 的手势签名库。
通过 npm 或 yarn 安装:
npm install vue-signature --save
# 或
yarn add vue-signature
在 Vue 组件中引入并使用:
<template>
<div>
<vue-signature ref="signature" :sigOption="options" />
<button @click="save">保存签名</button>
<button @click="clear">清除签名</button>
</div>
</template>
<script>
import VueSignature from 'vue-signature';
export default {
components: { VueSignature },
data() {
return {
options: {
penColor: '#000000',
backgroundColor: '#ffffff'
}
};
},
methods: {
save() {
const signature = this.$refs.signature.save();
console.log(signature); // 输出 base64 格式的签名图像
},
clear() {
this.$refs.signature.clear();
}
}
};
</script>
使用 HTML5 Canvas 自定义实现
如果不想依赖第三方库,可以通过 HTML5 Canvas 实现手势签名功能。
在 Vue 组件中添加 Canvas 元素:
<template>
<div>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
@touchstart="startDrawing"
@touchmove="draw"
@touchend="stopDrawing"
></canvas>
<button @click="saveSignature">保存签名</button>
<button @click="clearCanvas">清除</button>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
canvas: null,
ctx: null
};
},
mounted() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
this.canvas.width = 400;
this.canvas.height = 200;
},
methods: {
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 = this.canvas.getBoundingClientRect();
const clientX = e.clientX || e.touches[0].clientX;
const clientY = e.clientY || e.touches[0].clientY;
return {
x: clientX - rect.left,
y: clientY - rect.top
};
},
saveSignature() {
const dataUrl = this.canvas.toDataURL('image/png');
console.log(dataUrl); // 输出 base64 格式的签名图像
},
clearCanvas() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
};
</script>
移动端适配
为了在移动端支持触摸事件,需要在 Canvas 上添加 @touchstart、@touchmove 和 @touchend 事件。
在 getPosition 方法中处理触摸事件坐标,确保兼容性。
保存签名数据
签名完成后,可以通过 canvas.toDataURL() 方法将画布内容转换为 base64 格式的图像数据。
可以将数据发送到服务器或存储在本地(如 localStorage)。
样式优化
为 Canvas 添加边框和背景色,提升用户体验:

canvas {
border: 1px solid #ddd;
background-color: #f9f9f9;
}
注意事项
- 确保 Canvas 的宽高在
mounted钩子中设置,避免渲染问题。 - 清除画布时使用
clearRect方法,而非重新初始化 Canvas。 - 移动端需测试触摸事件的兼容性,必要时添加
preventDefault防止页面滚动。






