实现签名的三个关键方法:
1.mousedown:当鼠标按下时开始绘制签名。
2.mousemove:鼠标移动时持续绘制。
3.mouseup:鼠标抬起时结束绘制。
html:
<div class="setSign">
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
></canvas>
</div>
<div class="btns">
<el-button @click="handleClose">取 消</el-button>
<el-button type="danger" @click="clearCanvas">清 空</el-button>
<el-button type="primary" @click="saveSignature">保 存</el-button>
</div>
js:
import { getSignNew, saveSignNew } from "@/api/common";
export default {
mixins: [],
components: {},
props: {},
data() {
return {
isDrawing: false,
canvas: null,
context: null,
savedImage: null,
queryObj: {},
};
},
created() {},
mounted() {
this.queryObj = this.$common.convertKeys(this.$route.query);
getSignNew(this.queryObj)
.then((data) => {
// 请求到签名的base64格式,如果是存在后端的图片那么需要自己转为base64
if (data && data.data.flag && data.data.datas.length > 0) {
this.savedImage = data.data.datas[0]["BASE64IMG"];
var bgImg = new Image();
bgImg.src = this.savedImage;
bgImg.onload = () => {
this.$nextTick(() => {
// 获取容器的宽高
let box = document.querySelector(".setSign");
let w = box.clientWidth;
let h = box.clientHeight;
// 给容器设置padding
let padding = 20;
this.canvas = this.$refs.canvas;
this.canvas.height = h - padding; //获取画布的高度
this.canvas.width = w - padding; //获取画布的宽度
this.context = this.canvas.getContext("2d");
this.context.drawImage(bgImg, 0, 0);
this.context.lineWidth = 3; //设置线条宽度
this.context.strokeStyle = "#000"; //字体颜色
});
};
}
})
.catch((err) => {
this.$message.error("获取签名图片失败");
});
},
methods: {
startDrawing() {
this.isDrawing = true;
const rect = this.canvas.getBoundingClientRect();
this.context.beginPath();
this.context.moveTo(event.clientX - rect.left, event.clientY - rect.top);
},
draw() {
if (!this.isDrawing) return;
const rect = this.canvas.getBoundingClientRect();
this.context.lineTo(event.clientX - rect.left, event.clientY - rect.top);
this.context.stroke();
},
stopDrawing() {
this.isDrawing = false;
},
// 清空画布
clearCanvas() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.savedImage = null;
},
// 保存签名
saveSignature() {
// 获取图片的base64
this.savedImage = this.canvas.toDataURL();
let submitObj = {
base64img: this.savedImage,
...this.queryObj,
};
saveSignNew(submitObj).then((data) => {
if (data && data.data.flag) {
this.$message.success("保存成功");
}
});
},
},
};
</script>
效果图: