cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <p class="title">Stacking &amp; Animating Formula 1 Circuits in D3</p>
<p>
  <a href="https://codepen.io/jwasilgeo/pen/vaewyo" target="_blank">Part 1</a>
  |
  <span style="font-weight: bold; background-color: yellow;">Part 2</span>
  |
  <a href="https://codepen.io/jwasilgeo/pen/ajKEJQ" target="_blank">Part 3</a>
</p>

<svg viewBox="0 0 500 500"></svg>

<p class="emojis">&#x1F3CE; &#x1F3CE; &#x1F3CE; &#x1F3C1; &#x1F3C6; &#x1f60e;</p>

<p>Each Formula 1 circuit is rendered using its own D3 map projection that is rotated to that circuit's location on Earth. They appear to be stacked on top of each other because they are placed in the same SVG element.</p>

<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://unpkg.com/topojson-client@3.0.0/dist/topojson-client.min.js"></script>
            
          
!
            
              body {
  margin: 10px auto;
  text-align: center;
  font-size: 0.95em;
}

svg {
  stroke-linejoin: round;
  stroke-linecap: round;
  max-width: 78vmin;
}

svg .circuit-path {
  stroke-width: 2px;
  stroke: steelblue;
  fill: none;
  opacity: 0.4;
  cursor: pointer;
  transform-origin: center;
  transition: stroke-width 0.25s, stroke 0.25s, opacity 0.25s;
}

svg .circuit-path:hover {
  stroke-width: 5.5px;
  stroke: red;
  opacity: 0.6;
}

p {
  margin: 0 auto 5px auto;
  max-width: 80%;
}

p.title {
  font-weight: bold;
}

p.emojis {
  font-size: 1.5em;
}

            
          
!
            
              d3
  .json(
    "https://gist.githubusercontent.com/jwasilgeo/21a6a6b67e9dc14f28fa73bb2beb4a6e/raw/e29f0ef8f8d9832598b5429d6c5e2c6fa9d33666/F1_Circuits_2018_topojson.json"
  )
  .then(function(f1CircuitsTopoJson) {
    // topojson to geojson conversion
    var f1CircuitsGeoJson = topojson.feature(
      f1CircuitsTopoJson,
      f1CircuitsTopoJson.objects.F1_Circuits_2018
    );

    var svg = d3.select("svg");
    var dimensions = svg.attr("viewBox").split(" ");
    var width = dimensions[2];
    var height = dimensions[3];

    // create a child <path> element in the <svg> for every geojson circuit feature
    // and draw geojson features by converting (projecting) from geospatial coordinates
    // to svg space using a unique projection and geoPathGenerator for each circuit
    svg
      .selectAll("path")
      .data(f1CircuitsGeoJson.features)
      .enter()
      .append("path")
      .attr("d", function(geoJsonFeature) {
        // as each geojson feature is being drawn to an svg path,
        // use a unique projection that is rotated to the centroid of the geojson feature
        // which will make all the features "stacked" on top of each other in svg coordinate space
        var featureCentroid = d3.geoCentroid(geoJsonFeature);
        var featureCentroidRotation = [
          -featureCentroid[0],
          -featureCentroid[1]
        ];

        var projection = d3
          .geoMercator()
          // half of the parent <svg> width and height
          .translate([width / 2, height / 2])
          // this scale seems to work well for all the circuits
          .scale(2400 * width)
          // the projection rotation is what is most important for stacking features and
          // it is calculated by finding the centroid coordinates of the geojson circuit
          .rotate(featureCentroidRotation);

        // the geoPathGenerator is responsible for generating the "d" attribute that a <path> element needs
        var geoPathGenerator = d3.geoPath(projection);

        return geoPathGenerator(geoJsonFeature);
      })
      .classed("circuit-path", true)
      .style("transform", "scale(0.01)")
      // give each new <path> element a <title> child element to act as a tooltip
      .append("title")
      .text(function(d) {
        return d.properties.Name;
      });

    // transition in all the circuits' <path> elements
    // this will also start the endless yoyo of in/out transitions
    transformCircuitsYoyo("none", d3.easeBackOut);

    function transformCircuitsYoyo(transformValue, easing) {
      svg
        .selectAll("path.circuit-path")
        .interrupt()
        .each(function(d, idx, nodeList) {
          d3
            .select(this)
            .transition()
            .delay(100 * idx)
            .ease(easing)
            .style("transform", transformValue)
            .on("end", function() {
              while (idx < nodeList.length - 1) {
                return;
              }

              var nextTransformValue =
                transformValue === "scale(0.01)" ? "none" : "scale(0.01)";

              var nextEasing =
                easing === d3.easeBackIn ? d3.easeBackOut : d3.easeBackIn;

              var nextDelay = transformValue === "scale(0.01)" ? 250 : 2500;

              setTimeout(function() {
                transformCircuitsYoyo(nextTransformValue, nextEasing);
              }, nextDelay);
            });
        });
    }
  });

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console