Created
February 2, 2018 20:08
-
-
Save rtmalone/740e1f806342a6a0c6d7984fe47a6518 to your computer and use it in GitHub Desktop.
Make D3 SVG responsive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function responsivefy(svg) { | |
| // get container + svg aspect ratio | |
| var container = d3.select(svg.node().parentNode), | |
| width = parseInt(svg.style("width")), | |
| height = parseInt(svg.style("height")), | |
| aspect = width / height; | |
| // add viewBox and preserveAspectRatio properties, | |
| // and call resize so that svg resizes on inital page load | |
| svg.attr("viewBox", "0 0 " + width + " " + height) | |
| .attr("preserveAspectRatio", "xMinYMid") | |
| .call(resize); | |
| // to register multiple listeners for same event type, | |
| // you need to add namespace, i.e., 'click.foo' | |
| // necessary if you call invoke this function for multiple svgs | |
| // api docs: https://github.com/mbostock/d3/wiki/Selections#on | |
| d3.select(window).on("resize." + container.attr("id"), resize); | |
| // get width of container and resize svg to fit it | |
| function resize() { | |
| var targetWidth = parseInt(container.style("width")); | |
| svg.attr("width", targetWidth); | |
| svg.attr("height", Math.round(targetWidth / aspect)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment