How can I recalculate relative coordinates?

Viewed 119

I have a div block:

<div id="container"></div>

There is an SVG path inside this block with SVG circles. When I do click, I get relative coordinates to id="container". The top-left corner is 0,0.

The SVG element is always full width, height of container. But the SVG has its own view port.

How can I recalculate all points of the circle (x,y) of SVG to relative coordinates of #container?

<div id="container">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 1000" width="2000px" height="1000px">
    <circle cx="100" cy="100" r="10" fill="#4285f4"></circle>
  </svg>
</div>

I need to know the relative coordinates of each of circle, relative to the parent div.

JavaScript click is:

document.getElementById('container').onclick = function clickEvent(e) {
  var rect = e.target.getBoundingClientRect();
  var x = e.clientX - rect.left; //x position within the element.
  var y = e.clientY - rect.top; //y position within the element.
  console.log("Left? : " + x + " ; Top? : " + y + ".");
}

My attempt: https://jsfiddle.net/3g8un5w1/5/

I want to be able to transform in between position of the circle on canvas and mouse pointer position even when it's scaled via css.

1 Answers

Maybe just add id to the circle itself, and then read it's cx and cy attribute? If the div padding is set to 0, it should be a relative x and y. If padding is different, you need to add this padding to the x and y.

Plase note that it's x,y of center of the circle. Check the example below. At first it reads the x,y of the circle, then (after 2 seconds) sets it to 0,0. You can see, that it is relative to the div border (red).

If the div padding would be for example 10px, that value would still be 100, 100, but relativly to the container, you would have to add that 10, so it should return 100 + padding, 100 + padding (110,110). And setter should be 110 - padding, 110 - padding.

<div id="container" style="padding:0px; border:1px solid red;">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 1000" width="2000px" height="1000px">
    <circle cx="100" cy="100" r="10" fill="#4285f4" id="circle"></circle>
  </svg>
</div>

<script>
 console.log('Before:'); 
 console.log(document.getElementById('circle').getAttribute('cx') + ', '+ document.getElementById('circle').getAttribute('cy'));

 setTimeout(function(){
  console.log('After setting to 0,0.');  document.getElementById('circle').setAttribute('cx',0)
  document.getElementById('circle').setAttribute('cy',0)},2000);
</script>


EDIT AFTER COMMENT

Check the fiddle with scale example (based on your comment fiddle): https://jsfiddle.net/r7ckLfhv/

Related