vue实现签名
Vue 实现签名功能
在 Vue 中实现签名功能可以通过 HTML5 的 Canvas 元素结合触摸和鼠标事件来完成。以下是一个完整的实现方案:
安装依赖(可选)
如果需要更高级的签名功能,可以安装专门的签名库:
npm install vue-signature-pad
基础实现(使用原生 Canvas)
<template>
<div>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@touchstart="startDrawing"
@touchmove="draw"
@touchend="stopDrawing"
></canvas>
<button @click="clearCanvas">清除</button>
<button @click="saveSignature">保存</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.resizeCanvas()
window.addEventListener('resize', this.resizeCanvas)
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeCanvas)
},
methods: {
resizeCanvas() {
this.canvas.width = this.canvas.offsetWidth
this.canvas.height = this.canvas.offsetHeight
this.ctx.lineWidth = 2
this.ctx.lineCap = 'round'
this.ctx.strokeStyle = '#000000'
},
startDrawing(e) {
this.isDrawing = true
this.draw(e)
},
draw(e) {
if (!this.isDrawing) return
const rect = this.canvas.getBoundingClientRect()
const x = (e.clientX || e.touches[0].clientX) - rect.left
const y = (e.clientY || e.touches[0].clientY) - rect.top
this.ctx.lineTo(x, y)
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.moveTo(x, y)
},
stopDrawing() {
this.isDrawing = false
this.ctx.beginPath()
},
clearCanvas() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
},
saveSignature() {
const image = this.canvas.toDataURL('image/png')
// 可以发送到服务器或保存到本地
console.log(image)
}
}
}
</script>
<style>
canvas {
border: 1px solid #000;
width: 100%;
height: 300px;
background-color: #fff;
}
</style>
使用 vue-signature-pad 库
<template>
<div>
<SignaturePad ref="signaturePad" />
<button @click="clear">清除</button>
<button @click="save">保存</button>
</div>
</template>
<script>
import SignaturePad from 'vue-signature-pad'
export default {
components: {
SignaturePad
},
methods: {
clear() {
this.$refs.signaturePad.clearSignature()
},
save() {
const { isEmpty, data } = this.$refs.signaturePad.saveSignature()
if (!isEmpty) {
console.log(data) // 可以发送到服务器或保存
}
}
}
}
</script>
移动端优化
- 添加 touch 事件支持(已在基础实现中包含)
- 防止触摸滚动:
draw(e) { if (!this.isDrawing) return e.preventDefault() // 阻止默认行为防止页面滚动
// 其余绘制代码... }
#### 保存签名
签名可以转换为 Base64 格式或 Blob 对象:
```javascript
// 获取 PNG 格式的 Base64
const pngData = canvas.toDataURL('image/png')
// 获取 Blob 对象
canvas.toBlob(blob => {
const formData = new FormData()
formData.append('signature', blob, 'signature.png')
// 上传到服务器
}, 'image/png')
注意事项
- 响应式设计:确保 Canvas 在窗口大小变化时重新调整尺寸
- 线条样式:可根据需求调整 lineWidth、lineCap 和 strokeStyle
- 清除功能:提供清除画布的方法
- 移动端兼容:同时监听 touch 和 mouse 事件
- 保存格式:通常使用 PNG 格式保存签名图片







