Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizeable SVG elements with JavaScript and D3

does any one know any js code that would allow the svg element (entire contents too) to be resized depending on the size of the window set by the user. my users will want to view d3 graphics in a small customized view on their active desktops. while at the same time others will have it running full screen on their active desktops. this means that the graphs will need to resize them self depending on the users preference.

like image 604
DataDancer Avatar asked Jan 05 '13 08:01

DataDancer


2 Answers

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

Basically, you listen to the size of the window, apply a proportional transform to the g element that wraps all SVG elements, and adjust the size of the parent SVG. Call this code on pageload and on window resize, where "container" is the div holding 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 within a div.

The other way is to use the SVG viewBox, as demonstrated by Mike Bostock here - http://bl.ocks.org/harlantwood/raw/6900108/. This method is best if you are appending the SVG to the body, and I'm sure there is a way to use this method when placing the SVG inside of a div, but I was unable to find a solution, and thus created the above work around.

like image 80
jczaplew Avatar answered Oct 28 '22 11:10

jczaplew


You can adjust an svg.attr("width").attr("height") either on loading the page or on resizing, but you'd need additional behavior in your code to get the d3 elements to change with the new size.

You can also look into the .viewBox attribute of an svg object, which will scale the svg elements dynamically, but I've found its behavior among different browsers to be spotty:

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

like image 34
Elijah Avatar answered Oct 28 '22 10:10

Elijah