block by curran a683a360b9c78397a0db94ce15f473ce

Responding to Resize with Text

Full Screen

This example shows how to make a D3 visualization resizes and changes the size of text based on the size.

To experience the resize behavior, run this example full-screen and resize the browser.

forked from curran‘s block: Responding to Resize

index.html

<!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>