I have the the following code that successfully draws my text onto an SVG using d3.js:
var myRect = svgContainer.append("text")
.attr("x", 10)
.attr("y", 20)
.text("Lorem Ipsum")
.attr("font-weight", "bold")
.attr("fill", "white");
Now I want to get the bounding box of that text. How do I do it?? I tried the following:
console.log("getBBox = ", myRect.getBBox());
But it gave me this error:
Uncaught TypeError: myRect.getBBox is not a function
d3 has a function ".node ()" which returns the the underlying DOM node of the first item in the d3 selection: Show activity on this post. You can call "getBBox ()" on SVG elements to get their bounding box in terms of SVG coordinates.
You can call "getBBox ()" on SVG elements to get their bounding box in terms of SVG coordinates.
A boolean value indicating that the stroke should be included in the bounding box, defaults to false . A boolean value indicating that the markers should be included in the bounding box, defaults to false . A boolean value indicating that the bounding box should be clipped, defaults to false .
The returned value is a SVGRect object, which defines the bounding box. This value is irrespective of any transformation attribute applied to it or the parent elements. Found a problem with this page?
myRect is a d3 selection and not an html element.
Try this code:
myRect.node().getBBox();
var svgContainer = d3.select("svg");
var myRect = svgContainer.append("text")
.attr("x", 10)
.attr("y", 20)
.text("Lorem Ipsum")
.attr("font-weight", "bold")
.attr("fill", "white");
console.log("getBBox = ", myRect.node().getBBox());
svg{
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="800"></svg>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With