1、在PC端实现电子签名,并生成透明底的签名图片,demo如下:
<template>
<div>
<div class="container">
<canvas
ref="canvas"
:width="canvasWidth"
:height="canvasHeight"
@mousedown="startDraw"
@mousemove="draw"
@mouseup="finishDraw"
></canvas>
<button @click="clear" class="mr20 mt20">清除</button>
<button @click="saveSign" class="mt20">保存</button>
<div>
<img :src="signImg" alt="">
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
canvasWidth: 600,
canvasHeight: 300,
drawing: false,
signImg: null
};
},
methods: {
startDraw(event) {
this.drawing = true;
const canvas = this.$refs.canvas;
this.ctx = canvas.getContext('2d');
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.stroke();
}
},
finishDraw() {
this.drawing = false;
},
clear() {
const canvas = this.$refs.canvas;
this.ctx.clearRect(0, 0, canvas.width, canvas.height);
},
// 保存签名数据
saveSign() {
this.signImg = this.$refs.canvas.toDataURL();
}
}
};
</script>
<style scoped>
.container{
width: 600px;
height: 300px;
margin: 0 auto;
border: 1px solid #999;
margin: 0 auto;
margin-top: 200px;
border-radius: 5px;
}
.mr20{
margin-right: 20px;
}
.mt20{
margin-top: 20px;
}
</style>
2、效果