业务场景
分析
- 考虑用户会通过手机或者PC端进行操作,因此需要在事件中考虑手机端部分
思路
- 通过一个对话框的形式利用
Canvas
生成图片并通过toDataURL()
转换成Base64
的形式保存下来提交给后端进行保存
最终效果
实际效果展示
![组件效果](https://i-blog.csdnimg.cn/blog_migrate/a75eed758049c13b60ef280c268fea87.png)
![组件效果](https://i-blog.csdnimg.cn/blog_migrate/1b3d3a7037317051bae371df3793390a.png)
![电子签名](https://i-blog.csdnimg.cn/blog_migrate/f2d5a34b23e8bea686338c29ae0c5b7e.png)
实现
export default {
name: 'ESignature',
data() {
return {
points: [],
canvasTxt: null,
stage_info: [],
startX: 0,
startY: 0,
moveY: 0,
moveX: 0,
isDown: false,
strokeStyle: '#000',
lineWidth: 2
}
},
mounted() {
this.initCanvas()
},
methods: {
initCanvas() {
let canvas = this.$refs.canvasF
canvas.height = this.$refs.canvasHW.offsetHeight - 20
canvas.width = this.$refs.canvasHW.offsetWidth - 20
this.canvasTxt = canvas.getContext('2d')
this.stage_info = canvas.getBoundingClientRect()
},
mouseDown(ev) {
ev = ev || event
ev.preventDefault()
if (ev) {
let obj = {
x: ev.offsetX,
y: ev.offsetY
}
this.startX = obj.x
this.startY = obj.y
this.canvasTxt.beginPath()
this.canvasTxt.moveTo(this.startX, this.startY)
this.canvasTxt.lineTo(obj.x, obj.y)
this.canvasTxt.stroke()
this.canvasTxt.closePath()
this.points.push(obj)
this.isDown = true
}
},
mouseMove(ev) {
ev = ev || event
ev.preventDefault()
if (this.isDown) {
let obj = {
x: ev.offsetX,
y: ev.offsetY
}
this.moveY = obj.y
this.moveX = obj.x
this.canvasTxt.strokeStyle = this.strokeStyle
this.canvasTxt.lineWidth = this.lineWidth
this.canvasTxt.beginPath()
this.canvasTxt.moveTo(this.startX, this.startY)
this.canvasTxt.lineTo(obj.x, obj.y)
this.canvasTxt.stroke()
this.canvasTxt.closePath()
this.startY = obj.y
this.startX = obj.x
this.points.push(obj)
}
},
mouseUp(ev) {
ev = ev || event
ev.preventDefault()
if (ev) {
let obj = {
x: ev.offsetX,
y: ev.offsetY
}
this.canvasTxt.beginPath()
this.canvasTxt.moveTo(this.startX, this.startY)
this.canvasTxt.lineTo(obj.x, obj.y)
this.canvasTxt.stroke()
this.canvasTxt.closePath()
this.points.push(obj)
this.points.push({ x: -1, y: -1 })
this.isDown = false
}
},
handleGoBack() {
this.handleOverwrite()
this.$emit('on-back')
},
handleOverwrite() {
this.canvasTxt.clearRect(0, 0, this.$refs.canvasF.width, this.$refs.canvasF.height)
this.points = []
},
}
}