# canvas实现手写签名
canvas实现手写签名其实就是透过鼠标滑动获取坐标来连续的画线。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写签名</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
width: 100vw;
height: 100vh;
}
.index {
width: 100%;
height: 100%;
}
canvas {
width: 100vw;
height: 90vh;
border: 1px solid #ccc;
}
.index-btn {
display: flex;
align-items: center;
justify-content: space-around;
width: 100%;
height: 5vh;
}
</style>
</head>
<body>
<div class="index">
<canvas id="canvas" ontouchstart="touchStart(event)" ontouchmove="touchMove(event)" ontouchend="touchEnd(event)"></canvas>
<div class="index-btn">
<button onclick="clearSign()">重绘</button>
<button onclick="saveSign()">保存</button>
</div>
</div>
<script>
var body = document.getElementsByTagName("body")[0];
var canvas = document.getElementById("canvas");
var cw = body.offsetWidth;
var ch = body.offsetHeight * 90 / 100;
canvas.width = cw;
canvas.height = ch;
var ctx = canvas.getContext("2d");
setLine();
ctx.beginPath();
var startX = 0;
var startY = 0;
var moveX = 0;
var moveY = 0;
var isSign = false;
function touchStart(e) {
isSign = true;
startX = e.changedTouches[0].pageX;
startY = e.changedTouches[0].pageY;
ctx.moveTo(startX, startY);
}
function touchMove(e) {
moveX = e.changedTouches[0].pageX;
moveY = e.changedTouches[0].pageY;
ctx.lineTo(moveX, moveY);
ctx.stroke(); // 描边
}
function touchEnd(e) {
console.log('书写完毕');
}
function setLine() {
ctx.strokeStyle = "red";
ctx.lineWidth = 5;
ctx.lineCap = "round";
}
function clearSign() {
isSign = false;
// ctx.clearRect(0, 0, cw, ch);
canvas.width = cw;
canvas.height = ch;
setLine();
}
function saveSign() {
if (!isSign) return
var imgURL = canvas.toDataURL("image/png");
console.log(imgURL);
}
</script>
</body>
</html>