Canvas 实现电子签名
Canvas 实现电子签名,并返回 Base64 数据
<template>
<div>
<canvas id="canvas" ref="canvasF" @mousedown="mouseDown" @mousemove="mouseMove" @mouseup="mouseUp"></canvas>
</div>
</template>
<script>
export default {
name: 'SignatureSketchpadComponent',
data(){
return{
points: [],
canvasTxt: null,
stage_info: [],
startX: 0,
startY: 0,
moveY: 0,
moveX: 0,
isDown: false,
strokeStyle: '#000',
lineWidth: 2,
canvas:this.$refs.canvasF,
}
},
mounted() {
this.$nextTick(() => {
this.initCanvas()
})
},
methods:{
/**
* @description 初始化Canvas
*/
initCanvas() {
this.canvas = this.$refs.canvasF
// 获取画布的高度
this.canvas.height = 500
// 获取画布的宽度
this.canvas.width = 800
// 创建 context 对象
this.canvasTxt = this.canvas.getContext('2d')
this.stage_info = this.canvas.getBoundingClientRect()
},
/**
* @description: 鼠标按下事件 - 准备绘画
* @param ev
*/
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
}
},
/**
* @description: 鼠标移动事件 - 开始绘画
* @param ev
*/
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)
}
},
/**
* @description: 松开鼠标事件 - 停止绘画
* @param ev
*/
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
}
this.$emit('SignatureSketchpadComponentResult',this.canvas.toDataURL('image/png'))
},
}
}
</script>
<style scoped>
</style>