Vue Canvas 簽名是一種基于 Vue.js 框架以及 HTML5 Canvas 技術所實現的簽名功能。通過在 Canvas 上用戶可以自由地進行繪圖,簽寫并保存自己的簽名。我們可以很方便地將這個功能應用于數字簽名、電子合同、電子表單等場景中,達到優化用戶體驗、提高工作效率和安全性的目的。
下面是實現 Vue Canvas 簽名的代碼段:
<template>
<div>
<canvas ref="canvas" width="400" height="300" style="border: 1px solid #eee;"></canvas>
<button @click="clear">清除</button>
<button @click="save">保存</button>
</div>
</template>
<script>
export default {
data() {
return {
drawing: false,
lastX: 0,
lastY: 0,
}
},
mounted() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
canvas.addEventListener('mousedown', (e) => {
this.drawing = true
this.lastX = e.pageX - canvas.offsetLeft
this.lastY = e.pageY - canvas.offsetTop
})
canvas.addEventListener('mousemove', (e) => {
if (this.drawing) {
const x = e.pageX - canvas.offsetLeft
const y = e.pageY - canvas.offsetTop
ctx.beginPath()
ctx.moveTo(this.lastX, this.lastY)
ctx.lineTo(x, y)
ctx.stroke()
this.lastX = x
this.lastY = y
}
})
canvas.addEventListener('mouseup', () => {
this.drawing = false
})
canvas.addEventListener('touchstart', (e) => {
e.preventDefault()
this.drawing = true
this.lastX = e.touches[0].pageX - canvas.offsetLeft
this.lastY = e.touches[0].pageY - canvas.offsetTop
})
canvas.addEventListener('touchmove', (e) => {
e.preventDefault()
if (this.drawing) {
const x = e.touches[0].pageX - canvas.offsetLeft
const y = e.touches[0].pageY - canvas.offsetTop
ctx.beginPath()
ctx.moveTo(this.lastX, this.lastY)
ctx.lineTo(x, y)
ctx.stroke()
this.lastX = x
this.lastY = y
}
})
canvas.addEventListener('touchend', () => {
this.drawing = false
})
},
methods: {
clear() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
},
save() {
const canvas = this.$refs.canvas
const link = document.createElement('a')
link.download = 'signature.png'
link.href = canvas.toDataURL()
link.click()
},
},
}
</script>
通過上面的代碼,我們實現了在 Canvas 上事件的監聽,使用戶可以通過鼠標對 Canvas 進行繪圖,最終生成簽名并保存為 PNG 圖片文件。