第一次接触这个移动端签名,知道用canvas但是canvas不精通。所以canvas的代码是找的别人的,本来想附上之前的链接的但是找不到了,抱歉。
你能点进来说明你目前也被这个问题困扰着,我以我个人的理解说一下思路。
大家都会怎么去签名,但是问题就在横屏和竖屏的问题上。
1、先写好横屏和视屏的样式(横屏的时候正常布局就行,不用竖着布局,只是页面的宽高变化了,样式上不会有太大的影响的),2、用canvas的时候页面加载完成后回初始化canvas容器,当页面点击进去的时候是竖屏,横屏的时候初始化的canvas宽高会不符合横屏,这时候我们要判断,横竖屏转换的时候重新加载页面,这样初始化出来的canvas容器是符合我们当前屏幕的,也不用去考虑用户手机有没有锁定竖屏,或者是没有锁定竖屏(横屏)。
3、监听手机有没有横竖屏切换
mounted(){
this.lineCanvas({
el: this.$refs.canvas,//绘制canvas的父级div
clearEl: this.$refs.clearCanvas,//清除按钮
saveEl: this.$refs.saveCanvas,//保存按钮
});
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", this.resize, false);
},
resize(){
location.reload()
},
lineCanvas(obj) {
this.linewidth = 2;
this.color = "#000000";
this.background = "#ffffff";
for (var i in obj) {
this[i] = obj[i];
}
this.canvas = document.createElement("canvas");
let that = this
setTimeout(function(){
that.el.children[0]
if(!that.el.children[0]){
that.el.appendChild(that.canvas);
}
that.cxt = that.canvas.getContext("2d");
//这里去判断是不是横屏,以设置canvas容器的宽高
//这个很重要
//竖屏
if (window.orientation === 180 || window.orientation === 0) {
that.canvas.width = that.el.clientWidth
that.canvas.height = that.el.clientHeight;
}
//横屏的时候我设置的高度是200,这个单位是px
if (window.orientation === 90 || window.orientation === -90 ){
that.canvas.width = that.el.clientWidth
that.canvas.height = 200
}
that.cxt.fillStyle = that.background;
that.cxt.fillRect(0, 0, that.canvas.width, that.canvas.width);
that.cxt.strokeStyle = that.color;
that.cxt.lineWidth = that.linewidth;
that.cxt.lineCap = "round";
// that.canvas.width = 220
// that.canvas.height = that.el.clientHeight;
},50)
//开始绘制
this.canvas.addEventListener("touchstart", function(e) {
e.preventDefault();
this.cxt.beginPath();
this.cxt.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
}.bind(this), false);
//绘制中
this.canvas.addEventListener("touchmove", function(e) {
e.preventDefault();
this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
this.cxt.stroke();
}.bind(this), false);
//结束绘制
this.canvas.addEventListener("touchend", function(e) {
e.preventDefault();
this.cxt.closePath();
let imgBase64 = this.canvas.toDataURL();
//console.log(imgBase64);
this.signSrc= imgBase64;
}.bind(this), false);
//清除画布
this.clearEl.addEventListener("click", function(e) {
e.preventDefault();
this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
}.bind(this), false);
//保存图片,直接转base64
//因为我们的UI图没有保存这个按钮,只有确定按钮,所以在这里我直接调用了保存签名图片的接口
this.saveEl.addEventListener("click", function() {
let imgBase64 = this.canvas.toDataURL();
this.signSrc= imgBase64;
let params = {
sessionId: this.sessionId,
template_id : this.template_id,
signImg:imgBase64,
};
this.$axios.post(process.env.VUE_APP_URL,{'cmd':'***','value':params})
.then((res) => {
if(res.data.code === 200){
Toast.success(res.data.msg);
this.$router.go(-1)
}else{
this.resCode = res.data.code
this.InvalidId(this.resCode)
Toast.fail(res.data.msg);
}
})
}.bind(this), false);
},
横屏样式
竖屏样式