Skip to content

Instantly share code, notes, and snippets.

@curran
Last active February 28, 2017 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/a683a360b9c78397a0db94ce15f473ce to your computer and use it in GitHub Desktop.
Save curran/a683a360b9c78397a0db94ce15f473ce to your computer and use it in GitHub Desktop.
Responding to Resize with Text
license: mit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dynamic Size Example</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
/* Make the chart container fill the page using CSS. */
#chart {
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
</style>
</head>
<body>
<div id="chart"></div>
<script>
var chartDiv = document.getElementById("chart");
var svg = d3.select(chartDiv).append("svg");
function redraw(){
// Extract the width and height that was computed by CSS.
var width = chartDiv.clientWidth,
height = chartDiv.clientHeight;
// Use the extracted size to set the size of an SVG element.
svg
.attr("width", width)
.attr("height", height);
// Draw an X to show that the size is correct.
var text = svg.selectAll("text").data([1]);
text
.enter().append("text")
.attr("text-anchor", "middle")
.text("Resizing Text!")
.merge(text)
.attr("x", width / 2)
.attr("y", height / 2)
.attr("font-size", (width * 0.007) + "em");
// Alternative behaviors:
// // Driven by height.
// .attr("font-size", (height * 0.007) + "em");
// // Driven by average of width and height.
// .attr("font-size", ((width + height)/2 * 0.007) + "em");
}
// Draw for the first time to initialize.
redraw();
// Redraw based on the new size whenever the browser window is resized.
window.addEventListener("resize", redraw);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment