JavaScript實現移動端簽字功能

本文實例為大傢分享瞭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="'+%20file%20+%20'" 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);
}

效果

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: