Mutable SVG Elements with JavaScript and D3

Does anyone know any js code that would allow changing the svg element (all contents too) depending on the size of the window set by the user. my users will want to view d3 graphics in a small customizable view on their active desktops. while others will work in full screen on their active desktops. this means that the graphs will have to change them independently, depending on the preferences of users.

+6
source share
2 answers

I put together a demo of this desired behavior a few days ago. Take a look here - http://bl.ocks.org/4444770

Basically, you listen to the size of the window, apply a proportional transform to the g element, which wraps all the SVG elements, and adjusts the size of the parent SVG. Call this code in pageload and in the resize window, where "container" is the div containing the SVG:

d3.select("g").attr("transform", "scale(" + $("#container").width()/900 + ")"); $("svg").height($("#container").width()*0.618); 

This is a good method if your SVG is placed in a div.

Another way is to use the SVG viewBox, as shown here by Mike Bostock - http://bl.ocks.org/harlantwood/raw/6900108/ . This method is best if you add SVG to the body, and I'm sure there is a way to use this method when placing SVG inside a div, but I could not find a solution and thus created the above to work around.

+10
source

You can customize svg.attr ("width"). attr ("height") is either on page load or when resizing, but you will need additional behavior in your code to resize d3 elements using the new size.

You can also examine the .viewBox attribute of the svg object, which will scale the svg elements dynamically, but I found that its behavior among different browsers is spotty:

http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute

+2
source

All Articles