简体   繁体   中英

Why doesn't this code work for an svg element?

This code works well when i have it set as a canvas. But when i want to use it on an svg element, i get nothing. What i am trying to do is get the mouse coordinates relative to the canvas but then draw svg shapes depending on where the user clicks.

It works with this html:

<section class=chartArea>
    <canvas id=svg></canvas>
</section>

This html does not work:

<section class=chartArea>
   <svg id=svg></svg>
</section>

javascript:

svg = document.getElementById("svg");

function relMouseCoords(event){
  var totalOffsetX = 0; //coordinates of corner of canvas
  var totalOffsetY = 0;
  var canvasX = 0;
  var canvasY = 0;
  var svg = this; //what called the event

  do{
      totalOffsetX += svg.offsetLeft - svg.scrollLeft; //relative coordinates
      totalOffsetY += svg.offsetTop - svg.scrollTop;
  }
  while(svg = svg.offsetParent)

  canvasX = event.pageX - totalOffsetX;
  canvasY = event.pageY - totalOffsetY;

  point = {x:canvasX, y:canvasY};

  console.log(canvasX + " " + canvasY);

  return point; //object returned
}

svg.addEventListener('mousemove', relMouseCoords);

According to the CSSOM specification offsetLeft and offsetTop are html only properties and do not exist for SVG elements.

Firefox implements this correctly but Chrome does not.

You'd be better off using getBoundingClientRect instead I think.

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