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>
  |
  <a href="https://codepen.io/jwasilgeo/pen/EpvrdB" target="_blank">Part 2</a>
  |
  <span style="font-weight: bold; background-color: yellow;">Part 3</span>
</p>

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

<p>The 2018 Formula 1 circuits have already been stacked on top of each other. But instead of a crazy mess of noodles, we only show 1 at a time and animate endlessly to the next circuit's shape.</p>
<p>The <a href="https://github.com/veltman/flubber" target="_blank">flubber</a> library helps make the D3 SVG shape animations smooth and ultra super duper nice for maximum winning.</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>
<script src="https://unpkg.com/flubber@0.4.2/build/flubber.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;
  transform-origin: center;
  transition: stroke-width 0.25s, stroke 0.25s, opacity 0.25s;
}

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

p.title {
  font-weight: bold;
}

            
          
!
            
              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 an array, called "allCircuitPaths", containing the svg path information (the "d" attribute) for each circuit geojson

    // similarly to the "Step 1" and "Step 2" codepen examples,
    // each geojson feature uses 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

    // but here we can skip immediately converting geojson features to child <path> elements,
    // which is normally done in a D3 mapping (or charting) workflow,
    // and instead just create an array of the minimum info we need: the svg path information (the "d" attribute)
  
    // ultimately we will only render a single svg <path> element
    // and change/transition its own "d" attribute with the information in this "allCircuitPaths" array
    var allCircuitPaths = f1CircuitsGeoJson.features.map(function(
      geoJsonFeature
    ) {
      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 (eventually) needs
      var geoPathGenerator = d3.geoPath(projection);

      return geoPathGenerator(geoJsonFeature);
    });

    // create a single child <path> element in the <svg>
    // and set its "d" attribute value as the "d" shape of the first F1 circuit
    // and get a D3js reference to this <path> element
    var pathElementToAnimate = svg
      .append("path")
      .attr("d", allCircuitPaths[0])
      .classed("circuit-path", true);

    // using the single <path> element that was just created,
    // cycle endlessly over each svg path info contained in the "allCircuitPaths" array
    // and change/transition the "d" attribute value with a smooth animation assited by flubber
    animateTheCircuits(pathElementToAnimate, allCircuitPaths);
  });

function animateTheCircuits(pathElementToAnimate, allCircuitPaths) {
  // modify the info array in-place to achieve continuous cycling
  var start = allCircuitPaths.shift();
  var end = allCircuitPaths[0];
  allCircuitPaths.push(start);

  var interpolator = flubber.interpolate(start, end);

  pathElementToAnimate
    .transition()
    .duration(1250)
    .delay(1000)
    .attrTween("d", function() {
      return interpolator;
    })
    .on("end", function() {
      // rinse and repeat
      animateTheCircuits(pathElementToAnimate, allCircuitPaths);
    });
}

            
          
!
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