Reputation: 14309
I have a main SVG and can't find the right way to get its offset taking into account other page elements and scrolling.
For example, using the solution explained in this page and doing the following I get {"x":null,"y":null}
:
console.log(JSON.stringify(getPosition(d3.select('svg').node())));
I need a way to get the left and top offsets because when I use getBoundingClientRect
on mouse movements it returns absolute page coordinates and not zero based within the main SVG so I have no way to tell the left or top offsets to normalize it to zero.
For example, in this case:
<body>
<img width="600" height="600" />
<svg width="1500" height="650"/>
</body>
I would need to get the 600 top offset plus the scrolling which I get from document.documentElement.scrollTop
but I can't find a way to get the 600 Y offset from any d3js API.
Upvotes: 2
Views: 366
Reputation: 102174
You cannot use the solution proposed in the page you linked because SVG does not support element.offsetTop.
An easy alternative is using the property top
of Element.getBoundingClientRect():
const svg = d3.select("svg");
const offset = svg.node().getBoundingClientRect().top;
console.log(offset)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<img width="600" height="600"/>
<svg width="1500" height="650"/>
If you still want to use offsetTop
, wrap the SVG in an HTML container, like a <div>
:
const svg = d3.select("svg");
const offset = svg.node().parentNode.offsetTop;
console.log(offset)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<img width="600" height="600" />
<div>
<svg width="1500" height="650" />
</div>
Upvotes: 4