简体   繁体   English

用鼠标在画布上绘制多边形:站点设计中包含div时出现坐标问题

[英]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. 如果将div设置在位:fixed,就没有问题。

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): 试试我的“简单”鼠标代码(简单,因为它没有考虑边框/填充/ HTML偏移):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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