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!
Already found a solution. Directly call
canvas.getBoundingClientRect()
可以获取到canvas
to position relative to the viewport.