前言:
在上一篇文章中讲到了如何使用canvas在PC端实现电子签名,下面我们稍微修改一下代码在h5端也可以实现
效果图:
实现思路:
- 使用canvas来实现手写签名的功能,然后将canvas转化为图片
- 通过监听touchstart/touchmove/touchend/touchcancel来计算滑动位置
html布局
<div class="container">
<div>
<button id="clear">清空画布</button>
<button id="imgInfo">保存签名</button>
</div>
<canvas id="canvas" width="300" height="300"></canvas>
<div class="imgs" id="imgs"></div>
</div>
css样式:
* {
margin: 0;
padding: 0;
}
#canvas {
border: 1px solid black;
margin: 0 auto;
}
javascript:
//1.获取canvas
var myCanvas = document.getElementById("canvas");
//获取2d对象
var ctx = myCanvas.getContext("2d");
//清空画布
var clear = document.getElementById("clear");
// 保存签名
var imgInfo = document.getElementById("imgInfo");
// 保存的盒子
var imgs = document.getElementById("imgs");
//控制线条是否画
var isMouseMove = false;
//线条位置
var lastX, lastY;
window.onload = function () {
initCanvas();
};
//初始化
function initCanvas() {
let offset = myCanvas.getBoundingClientRect();
var start = (e) => {
e.preventDefault();
isMouseMove = true;
drawLine(
e.changedTouches[0].clientX - offset.left,
e.changedTouches[0].clientY - offset.top,
false
);
};
let move = (e) => {
if (isMouseMove) {
drawLine(
e.changedTouches[0].clientX - offset.left,
e.changedTouches[0].clientY - offset.top,
true
);
}
};
let end = (e) => {
isMouseMove = false;
};
let cancel = (e) => {
isMouseMove = false;
};
myCanvas.addEventListener('touchstart', start)
myCanvas.addEventListener('touchmove', move)
myCanvas.addEventListener('touchend', end)
myCanvas.addEventListener("touchcancel", cancel)
}
//画线
function drawLine(x, y, isT) {
if (isT) {
ctx.beginPath();
ctx.lineWidth = 2; //设置线宽状态
ctx.strokeStyle = 'black'; //设置线的颜色状态
ctx.lineCap = 'round'
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
}
// 每次移动都要更新坐标位置
lastX = x;
lastY = y;
}
//清空画图
function clearCanvas() {
imgs.innerHTML = ""
ctx.beginPath();
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
ctx.closePath(); //可加入,可不加入
}
//保存图片
function saveImgInfo() {
var images = myCanvas.toDataURL('image/png');
imgs.innerHTML = `<img src='${images}'>`
}
clear.addEventListener("click", clearCanvas);
imgInfo.addEventListener("click", saveImgInfo);