search

Home  >  Q&A  >  body text

javascript - Use canvas to implement electronic signature, position the coordinates of the mouse in the canvas

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!

巴扎黑巴扎黑2752 days ago565

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-05-16 13:38:00

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

    reply
    0
  • Cancelreply