做移動端收集電子簽名項目的時候發現了一些坑:
1. 移動端的手指按下、移動、抬起事件跟PC端的鼠標按下、移動、彈起事件是不一樣的
2. canvas它的屬性寬高和樣式寬高是不一樣的,通過CSS來設置canvas的寬高會導致一些奇怪的問題
3. canvas的間距(如果有)會造成手指落點和實際繪畫的點有偏移,所以在開始繪畫的時候要先把畫筆移動到正確的位置
<canvas id="ESCanvas" width="400" height="400">該瀏覽器不支持canvas畫布</canvas>
//PC端鼠標繪畫代碼 var canvas = document.getElementById('ESCanvas'); var ctx = canvas.getContext('2d'); var paint = false; canvas.onmousedown =function (e) { paint = true; ctx.moveTo(e.pageX - this.offsetLeft, e.pageY - this.offsetTop); canvas.onmousemove = function (e) { if (paint) { ctx.lineTo(e.pageX - this.offsetLeft, e.pageY - this.offsetTop); ctx.stroke(); } } canvas.onmouseup = function (e) { paint = false; } }
//移動端手繪代碼
//阻止頁面拖動 document.body.addEventListener('touchmove', function (e) { e.preventDefault(); }, { passive: false }); var canvas = document.getElementById("ESCanvas"); var ctx = canvas.getContext("2d"); //頁面樣式 canvas.width = window.screen.width - 42;//左邊距20,右邊為對齊左邊留20,邊框左右各1 canvas.height = window.screen.height - 130;//頂邊距20,底邊距20,邊框左右各1,按鈕組68,按鈕組底邊距20 var l = canvas.offsetLeft; var t = canvas.offsetTop; canvas.ontouchstart = function (e) { ctx.beginPath(); ctx.moveTo(e.touches[0].pageX - l, e.touches[0].pageY - t); } canvas.ontouchmove = function (e) { ctx.lineTo(e.touches[0].pageX - l, e.touches[0].pageY - t); ctx.stroke(); } canvas.ontouchend = function (e) { ctx.closePath(); }
最后的頁面效果圖: