html5手写签名

时间:2022-06-21 05:15:41
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta content="width=device-width,initial-scale=1,maximum-scale=1" name="viewport" />
<title>sxqm</title>
<meta name="format-detection" content="telephone=no">
<script src="/assets/js/jquery.min.js" type="text/javascript"></script>
<script src="/assets/js/jquery.mobile.custom.min.js" type="text/javascript"></script>
</head>
<body>
<canvas id="myCanvas"></canvas>
<div>
<button onclick="clean();">清 空</button>
<button onclick="save();">生成图片</button>
</div>
</body>
</html>
var canvas, board;
canvas = document.getElementById('myCanvas');
canvas.height = 300;
canvas.width = 400; board = canvas.getContext('2d');
board.lineWidth = 1; //设置画笔粗细
board.strokeStyle = "#f00";
board.lineJoin = "round"; //设置画笔轨迹基于圆点拼接 var mousePress = false;
var last = null; function beginDraw(event) {
mousePress = true;
}
function endDraw(event) {
mousePress = false;
event.preventDefault();
last = null;
}
function drawing(event) {
event.preventDefault();
if (!mousePress) return;
var xy = GetPos(event);
if (last != null) {
board.beginPath();
board.moveTo(last.x, last.y);
board.lineTo(xy.x, xy.y);
board.stroke();
}
last = xy;
} function GetPos(event) {
var isTouch = event.type.indexOf('touch') >= 0 ? true : false;
var x = isTouch ? event.touches[0].pageX : event.offsetX + event.target.offsetLeft;
var y = isTouch ? event.touches[0].pageY : event.offsetY + event.target.offsetTop;
return { x: x, y: y };
} function save() {
var data = canvas.toDataURL("image/png"); //把canvas画板上的内容转成指定格式图片数据,并进行Base64编码
var img = new Image();
img.src = data;
$(document.body).append(img);
} function clean() {
board.clearRect(0, 0, canvas.width, canvas.height);
} canvas.onmousedown = beginDraw;
canvas.onmousemove = drawing;
canvas.onmouseup = endDraw;
canvas.addEventListener('touchstart', beginDraw, false);
canvas.addEventListener('touchmove', drawing, false);
canvas.addEventListener('touchend', endDraw, false);