js移动端签字功能 JavaScript实现移动端签字功能
、蒙昧 人气:0想了解JavaScript实现移动端签字功能的相关内容吗,、蒙昧在本文为您仔细讲解js移动端签字功能的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js,移动端,签字,下面大家一起来学习吧。
一、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); }
效果
加载全部内容