在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本文实例为大家分享了JavaScript实现移动端签字功能的具体代码,供大家参考,具体内容如下 一、html部分<div class="mui-content-padded"> <div class="mui-inline"><font style="font-family: '微软雅黑';font-size: 1.2rem;">验收人签字:</font></div> </div> <div class="mui-content-canvasDiv" style="overflow: hidden;"> <canvas id="myCanvas" width="660" height="360" style="border:1px solid #f2f2f2;"></canvas> <div class="saveimgs" id="saveImgDiv"></div> </div> myCanvas是签字的div,saveImgDiv是保存后回显的div。 二、页面初始化,添加div签字功能InitThis(); var mousePressed = false; var lastX, lastY; var ctx = document.getElementById('myCanvas').getContext("2d"); var c = document.getElementById("myCanvas"); var selected1, selected2; function InitThis() { // 触摸屏 c.addEventListener('touchstart', function(event) { console.log(1) if(event.targetTouches.length == 1) { event.preventDefault(); // 阻止浏览器默认事件,重要 mousePressed = true; Draw(event.touches[0].pageX - this.offsetLeft, event.touches[0].pageY - this.offsetTop, false); } }, false); c.addEventListener('touchmove', function(event) { console.log(2) if(event.targetTouches.length == 1) { event.preventDefault(); // 阻止浏览器默认事件,重要 if(mousePressed) { Draw(event.touches[0].pageX - this.offsetLeft, event.touches[0].pageY - this.offsetTop, true); } } }, false); c.addEventListener('touchend', function(event) { console.log(3) if(event.targetTouches.length == 1) { event.preventDefault(); // 阻止浏览器默认事件,防止手写的时候拖动屏幕,重要 mousePressed = false; } }, false); // 鼠标 c.onmousedown = function(event) { mousePressed = true; Draw(event.pageX - this.offsetLeft, event.pageY - this.offsetTop, false); }; c.onmousemove = function(event) { if(mousePressed) { Draw(event.pageX - this.offsetLeft, event.pageY - this.offsetTop, true); } }; c.onmouseup = function(event) { mousePressed = false; }; } function Draw(x, y, isDown) { if(isDown) { ctx.beginPath(); ctx.strokeStyle = selected2; ctx.lineWidth = selected1; ctx.lineJoin = "round"; ctx.moveTo(lastX, lastY); ctx.lineTo(x, y); ctx.closePath(); ctx.stroke(); } lastX = x; lastY = y; } 三、获取图片路径放到saveImgDiv里,签字回显逻辑var file = "http://10.1.31.173:8097/upload/" + iv[0].zjqm + "?v=" + new Date().getTime(); $("#saveImgDiv").append('<img src="'+ file + '" style="background:white" width="660" height="360">'); 四、保存用户签名,可以放在保存提交成功的回调里var saveimgs = document.getElementsByClassName("saveimgs")[0]; //保存签名图片 var image = c.toDataURL("image/png"); var ctximg = document.createElement("span"); ctximg.innerHTML = "<img src='" + image + "' alt='from canvas'/>"; if(saveimgs.getElementsByTagName('span').length >= 1) { var span_old = saveimgs.getElementsByTagName("span")[0]; saveimgs.replaceChild(ctximg,span_old) } else { saveimgs.appendChild(ctximg); } 效果 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持极客世界。 |
请发表评论