javascript - Use canvas to implement electronic signature, position the coordinates of the mouse in the canvas
巴扎黑
巴扎黑 2017-05-16 13:36:00
0
1
477

When trying to use canvas to implement an electronic signature, the coordinates of the mouse in the canvas cannot be accurately obtained.

let canvas = document.getElementById("canvas");
let cxt = canvas.getContext('2d');
canvas.onmousedown = function(ev){
    var ev = ev || window.event;
    cxt.moveTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetTop);
    document.onmousemove = function(ev){
      var ev = ev || window.event;
      cxt.lineTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetTop);
      cxt.stroke();
    };

    document.onmouseup = function(){
      document.onmousemove = null;
      document.onmouseup = null;
    };
};

Use ev.clientY to obtain the coordinates of the mouse, but canvas.offsetTop obtains the height from the parent element. And canvas is in a form with scroll bars, so it cannot be positioned accurately.

Thanks!

巴扎黑
巴扎黑

reply all(1)
巴扎黑

Already found a solution. Directly call canvas.getBoundingClientRect() 可以获取到 canvas to position relative to the viewport.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!