首先是html层
<van-cell-group class="margin_top"> <van-cell v-if="!signSrc" title="请您签名" class="span_bold placeholder_sign" v-model="ClickSign" @click="gotoSign" /> <van-cell v-else title="请您签名" class="span_bold" v-model="ClickSign" @click="gotoSign"> <div class="mySign"> <img :src="signSrc" alt /> <div class="ChangeSign" @click="resetSign">修改签名</div> </div> </van-cell> </van-cell-group> <!-- 提交的弹出框 --> <van-button type="default" round class="nextStep" size="large" @click="nextStep">提交</van-button> <van-dialog v-model="show" title="签名" class="sign_box"> <van-icon name="cross" @click="closeDialog" /> <div class="sign_text"> <canvas id="myCanvas" style="height:100%;100%"></canvas> </div> <van-button plain type="primary" @click="resetSign">重签</van-button> <van-button plain type="info" @click="saveSign" class="float_r">保存</van-button> </van-dialog>
然后是触发事件
// 点击签名 gotoSign() { let that = this; that.show = true; setTimeout(() => { that.lineCanvas(); }, 10); },
重点来了,画图方法,
// 封装电子签名 lineCanvas() { this.canvas = document.getElementById("myCanvas"); this.cxt = this.canvas.getContext("2d");this.cxt.fillStyle = "#ffffff";
this.canvas.width = document.querySelector("#myCanvas").scrollWidth;
this.canvas.height = document.querySelector("#myCanvas").scrollHeight;
this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.height); // 设置线条颜色 this.cxt.strokeStyle = "#000"; // 设置线条宽度 this.cxt.lineWidth = 1; // 改变线条末端线帽的样式,为每个末端添加圆形线帽,减少线条的生硬感 this.cxt.lineCap = "round"; // 指定条线交汇时为圆形边角 this.cxt.lineJoin = "round"; // 锯齿问题 this.cxt.shadowBlur = 2; this.cxt.shadowColor = "#000";
//开始绘制
this.canvas.addEventListener(
"touchstart",
function(e) {
this.showTip = false;
let rectObject = this.canvas.getBoundingClientRect();
this.cxt.beginPath();
// debugger
this.cxt.moveTo(
e.targetTouches[0].clientX - rectObject.left,
e.targetTouches[0].clientY - rectObject.top
);
}.bind(this),
false
);
//绘制中
this.canvas.addEventListener(
"touchmove",
function(e) {
let rectObject = this.canvas.getBoundingClientRect();
// debugger;
this.cxt.lineTo(
e.targetTouches[0].clientX - rectObject.left,
e.targetTouches[0].clientY - rectObject.top
);
this.cxt.stroke();
}.bind(this),
false
);
//结束绘制 this.canvas.addEventListener( "touchend", function() { this.cxt.closePath(); let imgBase64 = this.canvas.toDataURL(); this.FinishedImg = imgBase64; this.IsSign = true; }.bind(this), false ); },
最后是保存canvas画的图
// 提交 saveSign() { if (this.IsSign) { let imgBase64 = this.canvas.toDataURL(); this.signSrc = imgBase64; this.IsSign = this.signSrc; this.show = false; // 清除画布 this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height); } else { this.show = false; } console.log("保存"); },
因为是业务代码,不是自己写的demo,所以可能会有些没有的参数和没有定义的参数,如有需要,请自行修改。主要内容已经在上面了,其他的小细节,自己扣一下,也算对这块代码有理解。