做移动端电子签名发现canvas的 一些坑

做移动端收集电子签名项目的时候发现了一些坑:

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(); }

 最后的页面效果图:

posted @ 2019-03-27 13:50  marisen  阅读(3342)  评论(0编辑  收藏  举报