I am using d3js to find the width of an svg element the code given below:
<script> var body = d3.select("body"); console.log(body); var svg = body.select("svg"); console.log(svg); console.log(svg.style("width")); </script> <svg class="svg" height="3300" width="2550"> <image x="0" y="0" height="3300" width="2550" xlink:href="1.jpg"></image> <rect class="word" id="15" x="118" y="259" width="182" height="28" text="Substitute"></rect> </svg>
But it returned this error:
Uncaught TypeError: Cannot call method 'getPropertyValue' of null
I think, the svg variable is a null array.
How can I get the width of an svg element using d3js?
The <g> SVG element is a container used to group other SVG elements. Transformations applied to the <g> element are performed on its child elements, and its attributes are inherited by its children. We can create a group element with D3. js by appending a g element using any selection.
Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.
SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility.
svg. selectAll('rect') tells the browser to find the svg element and look inside it for any rectangles. If it finds rectangles, it returns them in a selection that is an array of elements. If it doesn't find any, it returns an empty selection, which is what will happen in this case.
<svg class="svg" height="3300" width="2550"> <image x="0" y="0" height="3300" width="2550" xlink:href="1.jpg"></image> <rect class="word" id="15" x="118" y="259" width="182" height="28" text="Substitute"></rect> </svg> <script> var body = d3.select("body"); console.log(body); var svg = body.select("svg"); console.log(svg); console.log(svg.style("width")); </script>
Just place your script after svg element is loaded by the browser and all will be fine.
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