canvas 电子签名
重绘,保存,移出,移入,点击
<template>
<div style="width: 100%;height: 100%;display: flex;flex-direction: column">
<div >
<el-button @click="clearCanvas" size="mini">重绘</el-button>
<el-button @click="saveSignature" size="mini">保存</el-button>
</div>
<canvas
ref="canvas"
:width="canvasWidth"
:height="canvasHeight"
@mousedown="startDrawing"
@mousemove="draw"
@mouseenter="inits"
@mouseup="finishDrawing"
></canvas>
</div>
</template>
<script>
export default {
data() {
return {
canvasWidth: 480,
canvasHeight: 300,
drawing: false,
signatureData: null
};
},
mounted() {
const canvas = this.$refs.canvas;
this.ctx = canvas.getContext('2d');
this.resetInit()
},
methods: {
// 开始绘制签名
startDrawing(event) {
this.drawing = true;
this.ctx.beginPath()
const x = event.offsetX;
const y = event.offsetY;
this.ctx.moveTo(x, y);
},
// 绘制签名
draw(event) {
if (this.drawing) {
const x = event.offsetX;
const y = event.offsetY;
this.ctx.lineTo(x, y);
this.ctx.lineCap = "round";
this.ctx.stroke();
}
},
// 移出内容
inits(){
this.drawing = false
},
// 完成绘制签名
finishDrawing() {
this.drawing = false;
},
// 清除Canvas上的内容 清除上下文
clearCanvas() {
const canvas = this.$refs.canvas;
// 重置上下文
this.ctx = canvas.getContext('2d')
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.resetInit()
this.ctx.beginPath()
this.signatureData = null
},
// 保存签名数据
saveSignature() {
this.signatureData = this.$refs.canvas.toDataURL();
this.$emit("returnAutograph",this.signatureData)
},
// 设置默认底图
resetInit(){
this.ctx.beginPath()
this.ctx.fillStyle = '#ccc'
// 设置底图上下文
this.ctx.fillRect(0,0,this.canvasWidth,this.canvasHeight)
this.ctx.font = "48px serif";
this.ctx.fillStyle = '#000'
this.ctx.strokeText("Hello world", 0, 0);
}
}
};
</script>
<style>
canvas{
border: 1px solid #4C4C4C ;
}
</style>