一. HTML
<el-dialog :visible.sync="dialogVisible" width="100%">
<div class="inDialog" id="inDialog">
<canvas id="can"></canvas>
<div class="btnBox">
<el-button class="move90" @click="clearDraw" round>清除</el-button>
<el-button class="move90" round>取消</el-button>
<el-button class="move90" ref="saveCanvas" id="saveCanvas" type="primary" round>确定</el-button>
</div>
</div>
</el-dialog>
二. JS
data里定义变量
canvas: "",
context: "",
watch: {
'dialogVisible': function () {
if (this.dialogVisible) {
this.$nextTick(() => {
setTimeout(() => {
this.canvas = document.getElementById('can')
this.context = this.canvas.getContext('2d')
this.canvas.width = document.getElementById('inDialog').clientWidth
this.canvas.height = document.getElementById('inDialog').clientHeight
this.context.fillStyle = "#fff"
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height)
this.context.strokeStyle = "#000"
this.context.lineWidth = 4
this.context.lineCap = 'round'
// 开始绘制
this.canvas.addEventListener('touchstart', (e) => {
this.context.beginPath()
this.context.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
})
// 绘制中
this.canvas.addEventListener('touchmove', (e) => {
e.preventDefault()
this.context.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
this.context.stroke()
})
// 结束绘制
this.canvas.addEventListener('touchend', () => {
this.context.closePath()
const imgBase64 = this.canvas.toDataURL()
this.signSrc = imgBase64
this.isSign = true
})
}, 300);
})
}
}
},
// 清空画布
clearDraw() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},