移动端电子签名
使用说明
小程序的签名,主要是使用canvas标签,在里面进行绘画
确保绘画区域
在HTML中,为了保证canvas绘画区域固定,我为canvas添加了一个盒子,将为它的父级添加padding,并将canvas的宽高设为100%,防止笔迹超出范围,并将提示文字定位到画布上。
html结构
<div class="protocol-name">
<div class="authorizer">授权人:</div>
<!-- 电子签名区域 -->
<div class="signature">
<canvas id="signEdit" ></canvas> !- - 真实绘画区域-->
<p class="sign-tips">温馨提示:请点击电子签名后,进行签名。</p> <!- - 提示信息-->
</div>
</div>
//css样式
/* 签名画布 */
.claim .claim-protocol .protocol-name .signature{
position: relative;
height: 2.35rem;
background: #fafafa;
padding:0.2rem;
}
.claim .claim-protocol .protocol-name #signEdit{
display: inline-block;
width: 100%;
height: 100%;
}
.claim .claim-protocol .protocol-name .sign-tips{
color: #a2a2a2;
font-size: 0.26rem;
position: absolute;
width: 100%;
text-align: center;
height: 100%;
left: 0;
top:0;
line-height: 2.35rem;
}
签名的具体函数封装
使用的时候,直接传入canvas画布对象和字体设置对象即可
// 签名
function draw(canvas, fontSize) {//canvas签名区域对象,fontSize:字体样式以及颜色
var start_x, start_y, move_x, move_y, end_x, end_y;//鼠标位置变化
var ctx = canvas[0].getContext("2d");//获取上下文
var t = $("#signEdit").offset().top;//canvas上边距
var l = $("#signEdit").offset().left;//canvas左边距
ctx.font = fontSize//设置字体属性
console.log(canvas.parents('.signature').width(), canvas.parents('.signature').height())
//按下
canvas.on("touchstart", function (e) {
$('.sign-tips').hide()
e.preventDefault()
start_x = e.touches[0].pageX - l;
start_y = e.touches[0].pageY - t;
//开始本次绘画
ctx.beginPath(); //画笔起始点
ctx.lineJoin = "round";//线条相交时拐角的类型
ctx.miterLimit = 360;//最大斜接长度
ctx.moveTo(start_x, start_y);
});
//移动
canvas.on("touchmove", function (e) {
$('.sign-tips').hide()
e.preventDefault()
move_x = e.touches[0].pageX - l;
move_y = e.touches[0].pageY - t;
//根据鼠标路径绘画
ctx.lineTo(move_x, move_y);
//立即渲染
ctx.stroke();
});
//松开
canvas.on("touchend", function (e) {
$('.sign-tips').hide()
e.preventDefault()
end_x = e.changedTouches[0].pageX - l;
end_y = e.changedTouches[0].pageY - t;
//创建从当前点到开始点的路径
ctx.closePath();
});
//生成签名照url
console.log(canvas[0].toDataURL())
// 清空画布 ,点击id名为clear-canvas的按钮清空画布
$('#clear-canvas').on('click', function (e) {
$('.sign-tips').show()
e.preventDefault()
console.log(canvas[0].clientWidth, canvas[0].clientHeight)
//清空画布时,为了保证所有自己清楚完毕,这里后两位数字采用的时父级的宽高
ctx.clearRect(0, 0, canvas.parents('.signature').width(), canvas.parents('.signature').height());
})
};
使用实例
我将提示信息的盒子,占满了整个canvas父级,给提示信息添加点击事件,相当于点击canvas盒子,使用了事件冒泡与事件委托的原理
//签名
//在这里点击签名提示信息
$('.sign-tips').on('click',function(e){
console.log(e.target)
$('.sign-tips').hide() //将提示信息隐藏
e.preventDefault() //阻止默认事件
let canvas=$('#signEdit')
draw(canvas)
})