7/14/2014 - 8:31 PM

Resizing D3 SVG

Resizing D3 SVG

How to create D3 visualizations that resize and scale well

When creating the SVG, add this bit of D3:

.attr("viewBox","0 0 960 500")

Then later in the code, add this bit of jQuery:

var chart = $("#chart"),
    aspect = chart.width() / chart.height(),
    container = chart.parent();
$(window).on("resize", function() {
    var targetWidth = container.width();
    chart.attr("width", targetWidth);
    chart.attr("height", Math.round(targetWidth / aspect));

The end.