function prevDrawStatement() { clearCanvas();//清除画布 canvasPaint.finish.innerHTML = "提交抄写"; canvasPaint.pencilBtn.style.display = 'block'; canvasPaint.secondState.style.display = 'block'; canvasPaint.tips.innerHTML = "(最后一步)请抄写屏幕上方引号内的确认语句"; canvasPaint.tips.style.color = 'red'; setTimeout(function () { canvasPaint.tips.style.color = '#666'; }, 2000); state = STATEMENT;//开始写句子 }
右上角有个移动签字板功能,这里实现的是左右移动,相关代码如下
function togglePencil() { if (canvasPaint.canPaint) { canvasPaint.canPaint = false; canvasPaint.pencilBtn.innerText = "使用签字笔"; //不能签字时应该把开始写字事件去掉,同时加上document事件 canvasPaint.canvas.removeEventListener('touchstart', startEventHandler, false); document.addEventListener('touchstart', documentStartEventHandler, {passive: false}); } else { canvasPaint.canPaint = true; canvasPaint.pencilBtn.innerText = "移动签字板"; //能签字时应该把开始写字事件绑定上去,同时去掉document事件 canvasPaint.canvas.addEventListener('touchstart', startEventHandler, {passive: false}); document.removeEventListener('touchstart', documentStartEventHandler, false); } } function documentStartEventHandler(event) { event.preventDefault(); canvasPaint.y = event.clientY; canvasPaint.top = parseFloat(canvasPaint.canvas.style.top);//画板距离顶部的值 document.addEventListener('touchmove', documentMoveEventHandler, {passive: false}); document.addEventListener('touchend', documentEndEventHandler, {passive: false}); } function documentMoveEventHandler(event) { event.preventDefault(); canvasPaint.newY = event.clientY - canvasPaint.y; if (!canvasPaint.canPaint) { canvasPaint.canvas.style.top = canvasPaint.newY + canvasPaint.top + 'px'; if (parseFloat(canvasPaint.canvas.style.top) > 0) {//限制边界 canvasPaint.canvas.style.top = 0 + 'px'; } } } function documentEndEventHandler(event) { event.preventDefault(); }
合成长句到协议中并显示最终图片
提交抄写按钮点击后执行下面的函数
function statementDraw(imgArr) { canvasPaint.context2.save(); canvasPaint.context2.translate(52, 690); canvasPaint.context2.rotate(270 * Math.PI / 180); canvasPaint.context2.drawImage(imgArr[0], 80, 50, 33, 33 * canvasPaint.ratio);//画反转后的名字 canvasPaint.context2.restore(); console.log(canvasPaint.canvas2.toDataURL()); document.getElementById('resultImg').setAttribute('src', canvasPaint.canvas2.toDataURL()); document.getElementById('resultImg').style.position = 'absolute'; document.getElementById('resultImg').style.left = 0; document.getElementById('resultImg').style.top = 0; document.getElementById('resultImg').style.zIndex = 50; }
在一个风和日丽的下午,刚准备下班,突然接到需求说要做一个在线签协议功能,当时心里想着不就百度一顿拷贝就完事了吗(因为我没用过canvas,所谓初生牛犊不怕虎 ),谁知做起来如此吃力,下面就来记录下历程。
协议模板
分析
如上图,需要做的就是做一个签字板可以在上面写字,写完后点击完成可以生成如上图的图片所示,把签好的字放到指定的位置。
做这个第一反应肯定就是使用canvas绘制路径
我的思路是:
一个字一个字写,每写一个字点一下记录,最后拼接,但想到用户体验问题就pass了这个思路。
最后的思路:一行可以写很多个字,可以让用户滑动canvas,一直写下去(因为协议模板最后还要抄写一段话)
canvas绘制路径--实现签名功能