canvas实现移动端手写签名功能
分类: 解决问题 9879 8
这是在一次项目需要用到手写签名的功能,具体代码:
<canvas>您当前浏览器不支持canvas,建议更换浏览器!</canvas>
<button>导出png</button>
<button>清空画布</button>
var canvas = document.querySelector('canvas'),
oBtn = document.querySelectorAll('button'),
ctx = canvas.getContext('2d');
var _x = 0,
_y = 0,
x = 0,
y = 0;
// 设置画布大小
canvas.width = 300;
canvas.height = 200;
// 开始绘制
canvas.addEventListener('touchstart', function (e) {
e.preventDefault();
_x = e.touches[0].pageX,
_y = e.touches[0].pageY;
// 路径开始
ctx.beginPath();
ctx.moveTo(_x - canvas.offsetLeft, _y - canvas.offsetTop);
// 路径移动
this.addEventListener('touchmove', function (e) {
x = e.touches[0].pageX,
y = e.touches[0].pageY;
ctx.lineTo(x - canvas.offsetLeft, y - canvas.offsetTop);
ctx.stroke();
});
});
// 导出图片
oBtn[0].onclick = function () {
var oImg = new Image();
ctx.drawImage(oImg, 0, 0);
oImg.src = canvas.toDataURL('image/png');
document.body.appendChild(oImg);
}
// 清空画布
oBtn[1].onclick = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
共 8 条评论关于 “canvas实现移动端手写签名功能”