<template>
<div>
<div class="canvas-box">
<canvas ref="signCanvas" width="700" height="400" @mousedown="handleStart" @mousemove="handleMove"
@mouseup="handleUp" v-show="!sign || sign == ''" style="margin:2px;"></canvas>
<img :src="sign" width="700" height="400" v-if="sign && sign != ''" style="margin:3px;" />
</div>
<el-button @click="saveSign" type="text" class="el-icon-check">保存</el-button>
<el-button @click="resetRect" type="text" class="el-icon-refresh">重绘</el-button>
</div>
</template>
<script>
export default {
data() {
return {
isSign: false,
sign: '',
signCanvas: '',
context: ''
}
},
methods: {
handleStart(e) {
this.isSign = true
this.signCanvas = this.$refs.signCanvas
this.context = this.signCanvas.getContext('2d')
const rect = this.context.canvas.getBoundingClientRect()
var ox = e.clientX - rect.left;
var oy = e.clientY - rect.top;
this.context.moveTo(ox, oy);
},
handleMove(e) {
if (this.isSign) {
this.context.lineWidth = 5;
const rect = this.context.canvas.getBoundingClientRect()
var ox2 = e.clientX - rect.left;
var oy2 = e.clientY - rect.top;
this.context.lineTo(ox2, oy2);
this.context.stroke();
}
},
handleUp(e) {
this.isSign = false
},
saveSign() {
let img = this.convertCanvasToImage(this.signCanvas)
this.sign = img.src
},
convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
},
resetRect() {
this.signCanvas = this.$refs.signCanvas
this.context = this.signCanvas.getContext('2d')
this.isSign = false
this.sign = ''
this.context.fillStyle = '#fff'
this.context.fillRect(0, 0, 705, 400)
this.context.beginPath();
},
}
}
</script>
<style>
.canvas-box {
display: inline-block;
text-align: center;
width: 710px;
height: 410px;
border: 1px solid #999;
border-radius: 10px;
}
</style>