移动端签字功能

发布时间:2023-05-02 12:30

实现移动端用户签名功能

一、html部分

验收人签字:

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(\'\');

四、保存用户签名,可以放在保存提交成功的回调里

var saveimgs = document.getElementsByClassName(\"saveimgs\")[0];

//保存签名图片
var image = c.toDataURL(\"image/png\");
var ctximg = document.createElement(\"span\");
ctximg.innerHTML = \"\'from\";
if(saveimgs.getElementsByTagName(\'span\').length >= 1) {
	var span_old = saveimgs.getElementsByTagName(\"span\")[0];
	saveimgs.replaceChild(ctximg,span_old)
} else {
	saveimgs.appendChild(ctximg);
}

效果

\"移动端签字功能_第1张图片\"

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号