Let's start with an overview of our Canvas application before we take it apart.
It's best to quickly get the HTML out of the way as it couldn't be much simpler. We have a div for the canvas at hand as well as our buttons:
<div id="canvas-map"></div>
<div id="controls">
<div class="flight-select" id="button-header">Pick number of flights:</div>
<button class="flight-select" data-flights="100">100</button>
<button class="flight-select" data-flights="1000">1,000</button>
<button class="flight-select" data-flights="5000">5,000</button>
<button class="flight-select" data-flights="10000">10,000</button>
<button class="flight-select" data-flights="15000">15,000</button>
<button class="flight-select" data-flights="20000">20,000</button>
<button class="flight-select" data-flights="25000">25,000</button>
<button class="flight-select" data-flights="30000">30,000</button>
</div>
Note that each button gets the same class selector as well as a data-flights attribute to pass on the number of flights each button represents. You will use this in a moment to load the right dataset!
Now let's look at the steps we take in the JavaScript to build this app in Canvas and see what changes to the flow we described previously for the SVG app. I have highlighted the parts we change for the Canvas flow and have removed the SVG parts (in brackets):
- You set up the Canvas and the context (instead of a container SVG), as well as the projection and the path generator for the map
- You load the map data and draw the map
- You listen to button events and load in the appropriate dataset depending on the button pressed
- You draw the airports and the world, as they are on the same Canvas and a redraw is cheap
- You calculate each plane’s origin and destination position as well as compute a path from origin to destination
- You sample way points along each plane’s path and store them in an array
- You set off the game loop (instead of using D3 transitions):
- clear the Canvas
- update the position
- draw the planes
- In the SVG example we restart a transition, once each plane has reached its destination. In our Canvas app this is part of the update step in the game loop.