canvas实现移动端手写签名功能

这是在一次项目需要用到手写签名的功能,具体代码:

HTML

1
2
3
<canvas>您当前浏览器不支持canvas,建议更换浏览器!</canvas>
<button>导出png</button>
<button>清空画布</button>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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);
}