发布时间:2023-05-02 12:30
实现移动端用户签名功能
验收人签字:
myCanvas是签字的div,saveImgDiv是保存后回显的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;
}
var file = \"http://10.1.31.173:8097/upload/\" + iv[0].zjqm + \"?v=\" + new Date().getTime();
$(\"#saveImgDiv\").append(\'\');
var saveimgs = document.getElementsByClassName(\"saveimgs\")[0];
//保存签名图片
var image = c.toDataURL(\"image/png\");
var ctximg = document.createElement(\"span\");
ctximg.innerHTML = \"\";
if(saveimgs.getElementsByTagName(\'span\').length >= 1) {
var span_old = saveimgs.getElementsByTagName(\"span\")[0];
saveimgs.replaceChild(ctximg,span_old)
} else {
saveimgs.appendChild(ctximg);
}