简体   繁体   中英

Drawing polygons in canvas with the mouse: coord issue when the div is included in the design of the site

I'm working with this script "Drawing polygons with the mouse" and it works very well. The issue I have is when I put the canvas in the design of my site. The canvas is thus now in relative position and the coords are wrong. I have a lag between my cursor and the draw…

If I set the div in position: fixed, there is no problem.

The positions are declared as follows:

canvas.addEventListener("click", function(e) {
    var x = e.clientX-canvas.offsetLeft;
    var y = e.clientY-canvas.offsetTop;  

How to fix this? How to put the canvas in my design and have the right coords?

Thank you very much!

Try my "simple" mouse code (simple because it does not take into account border/padding/HTML offset):

function getMouse(e, canvas) {
  var element = canvas, offsetX = 0, offsetY = 0, mx, my;

  // Compute the total offset
  if (element.offsetParent !== undefined) {
    do {
      offsetX += element.offsetLeft;
      offsetY += element.offsetTop;
    } while ((element = element.offsetParent));
  }

  // This isn't the best code because I am not adding padding and border style widths to offset. I'm just keeping it simple.

  mx = e.pageX - offsetX;
  my = e.pageY - offsetY;

  return {x: mx, y: my};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM