Skip to content Skip to sidebar Skip to footer

Click Event Coordinates In SVG

This HTML containing SVG:
&

Solution 1:

I've added to your code a function to detect the mouse position in SVG.

let svg = document.querySelector('svg')

function clicked(event) {
  let m = oMousePosSVG(event);
    console.log(m.x,m.y);
}

svg.addEventListener("click", clicked)


function oMousePosSVG(e) {
      var p = svg.createSVGPoint();
      p.x = e.clientX;
      p.y = e.clientY;
      var ctm = svg.getScreenCTM().inverse();
      var p =  p.matrixTransform(ctm);
      return p;
}
svg{border:1px solid}
<div class="container">
  <div class="spacer"></div>
  <svg>
    <g id="polygonGroup" transform="translate(80, 50)">
      <polygon points="-60,-10 -35,-30 -10,-10 -10,30 -60,30"></polygon>
      <polygon points="10,-10 35,-30 60,-10 60,30 10,30"></polygon>
      <polygon class="origin" points="-4,0 0,4 4,0 0,-4"></polygon>
    </g>
    <g id="textGroup" transform="translate(80, 50)" fill="red">
      <text x="-35" y="10">Text</text>
      <text x="35" y="10">Text</text>
    </g>
  </svg>
</div>

To read more about mouse detection in SVG I recommend this book: Using SVG with CSS3 and HTML5: Vector Graphics for Web Design

I hope it helps.


Post a Comment for "Click Event Coordinates In SVG"