Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the width of an svg element using d3js?

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?

like image 373
linto cheeran Avatar asked Oct 31 '13 15:10

linto cheeran


People also ask

Can we group SVG elements in 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.

How do I set height and width in SVG?

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.

What is SVG in d3js?

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.

What is SVG selectAll?

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.


1 Answers

<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.

like image 123
Andrew Surzhynskyi Avatar answered Sep 18 '22 12:09

Andrew Surzhynskyi