实现功能
git地址
参数说明
- dotSize:点的大小(在屏幕上点击留下的点大小,单位:px)
- minWidth: 线的最小宽度(单位:px,默认:0.5)
- maxWidth:线的最大宽度(单位:px,默认:2.5)
- throttle:节流(每次绘制两个点之间的时间,单位:ms,默认:16,注意:设置过大会显得很卡顿)
- minDistance:最小距离(每次绘制两个点之间的最小距离,单位:px,默认:5)
- backgroundColor:背景色(默认:#000)
- penColor:线条颜色(默认:#fff)
- velocityFilterWeight:根据速度控制线的weight(默认:0.7)
- onBegin:一笔开始时触发的事件
- onEnd:一笔结束时触发的事件
API说明
- toDataURL():保存为图片,默认保存为png,toDataURL("image/jpeg")-保存为jpg,toDataURL("image/svg+xml")-保存为svg
- isEmpty():签名是否为空
- clear():清空签名
-toData():返回签名点的数组
- fromData():
- off():解绑所有事件
- on():重新绑定所有事件
调整画布尺寸
- 给画布设置一个固定大小,有时签名会呈现一个被拉伸的状态,这是需要重新调整签名的尺寸,官方给出了方法,直接粘贴代码即可。
function resizeCanvas() {
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
signaturePad.clear(); // otherwise isEmpty() might return incorrect value
}
window.addEventListener("resize", resizeCanvas);
resizeCanvas();
使用中遇到的问题
1. 安装依赖后报错
- v3.0.0-beta.3版本有问题,建议使用v2.3.0(官方demo使用的是v2.3.0,活着直接用demo中的js)
使用代码
# index.html
<script type="text/javascript" src="js/lib/signature_pad.js"></script>
# signature.html
<span id="selfSign"></span>
<button class="button button-fill sign" data-action="sign">签名</button>
# signatureCtr.js
let signButton = document.querySelector("[data-action=sign]");
let dataURL = "";
signButton.addEventListener("click", function (event) {
SdicInterview.popup(
'<div class="popup sign-popup">' +
'<a class="color-indigo close-popup" data-popup=".sign-popup" style="font-size:25px;position:absolute;top:4px;right:10px;cursor:pointer;z-index:1"> <i class="fa fa-times"></i></a>' +
'<div id="signature-pad">' +
"<h1>专 家 签 名</h1>" +
'<canvas class="form-footer-signature"></canvas>' +
'<button class="button clear" data-action="clear">清除签名</button>' +
'<button class="button save close-popup" data-popup=".sign-popup" data-action="save-jpg">确定</button>' +
"</div>"
);
var wrapper = document.getElementById("signature-pad");
var clearButton = wrapper.querySelector("[data-action=clear]");
var canvas = wrapper.querySelector("canvas");
var saveJPGButton = wrapper.querySelector("[data-action=save-jpg]");
var signaturePad = new SignaturePad(canvas, {
backgroundColor: "#fff",
});
function resizeCanvas() {
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
signaturePad.clear();
}
window.onresize = resizeCanvas;
resizeCanvas();
clearButton.addEventListener("click", function (event) {
signaturePad.clear();
});
saveJPGButton.addEventListener("click", function (event) {
if (!signaturePad.isEmpty()) {
dataURL = signaturePad.toDataURL("image/jpeg");
document.getElementById("selfSign").innerHTML = '<img class="sign-img-sum" id="selfSign" src="' + dataURL + '" />';
}
});
});