There are some problems with your solution when compared with the solution in the answer you linked. You are getting the new size from the svg:
var targetWidth = chart.node().getBoundingClientRect().width;
which has the same size as before the resize event. Instead, in the linked answer the svg
element is inside a div
, and the targetWidth
is taken from the div
. Additionally, I think that approach is not valid for more complex svg
s (right now I don't know the reasons, TBH).
However, another option could be redraw the chart (see fiddle) on resize event:
// RESIZE
var aspect = width / height,
chart = d3.select('svg');
var container = d3.select('#container');;
d3.select(window)
.on("resize", function() {
var targetWidth = container.node().getBoundingClientRect().width;
var targetHeight = targetWidth / aspect;
d3.select('svg').remove();
var svg = d3.select("#container").append("svg")
.attr("width", targetWidth + margin.left + margin.right)
.attr("height", targetHeight + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
draw(svg, targetWidth, targetHeight);
});
This solution requires encapsulating in a function the code that draws the chart. Probably it's not very suitable in terms of computational resources, but maybe works for your purposes.