移动端手写签名功能
移动端手写签名
监听移动端touch事件,在canvas上完成签名绘制,然后将canvas转为base64图片。
以下为代码。
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>移动端手写签名</title>
<style type="text/css">
html,
body {
width: 100%;
height: 100%;
}
#canvas {
width: 100%;
height: 100%;
position: relative;
}
#canvas canvas {
display: block;
}
#clearCanvas {
width: 50%;
height: 40px;
line-height: 40px;
text-align: center;
position: absolute;
bottom: 0;
left: 0;
border: 1px solid #DEDEDE;
z-index: 1;
}
#saveCanvas {
width: 50%;
height: 40px;
line-height: 40px;
text-align: center;
position: absolute;
bottom: 0;
right: 0;
border: 1px solid #DEDEDE;
z-index: 1;
}
</style>
</head>
<body>
<div id="canvas">
<button id="clearCanvas">清除</button>
<button id="saveCanvas">保存</button>
</div>
<script type='text/javascript'>
window.onload = function () {
new lineCanvas({
el: document.getElementById("canvas"),//绘制canvas的父级div
clearEl: document.getElementById("clearCanvas"),//清除按钮
saveEl: document.getElementById("saveCanvas"),//保存按钮
// linewidth:1,//线条粗细,选填
// color:"black",//线条颜色,选填
// background:"#ffffff"//线条背景,选填
});
};
function lineCanvas(obj) {
this.linewidth = 1;
this.color = "#000000";
this.background = "#ffffff";
for (var i in obj) {
this[i] = obj[i];
};
this.canvas = document.createElement("canvas");
this.el.appendChild(this.canvas);
this.cxt = this.canvas.getContext("2d");
this.canvas.width = this.el.clientWidth;
this.canvas.height = this.el.clientHeight;
this.cxt.fillStyle = this.background;
this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.width);
this.cxt.strokeStyle = this.color;
this.cxt.lineWidth = this.linewidth;
this.cxt.lineCap = "round";
//开始绘制
this.canvas.addEventListener("touchstart", function (e) {
this.cxt.beginPath();
this.cxt.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
}.bind(this), false);
//绘制中
this.canvas.addEventListener("touchmove", function (e) {
this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
this.cxt.stroke();
}.bind(this), false);
//结束绘制
this.canvas.addEventListener("touchend", function () {
this.cxt.closePath();
}.bind(this), false);
//清除画布
this.clearEl.addEventListener("click", function () {
this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
}.bind(this), false);
//保存图片,直接转base64
this.saveEl.addEventListener("click", function () {
var imgBase64 = this.canvas.toDataURL();
console.log(imgBase64);
}.bind(this), false);
};
</script>
</body>
</html>
洗尽铅华始见金,褪去浮华归本真
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2022-04-04 【微信小程序】简单的手指拖拽效果
2022-04-04 【性能优化】统一更新与时时更新