Preamble
Let's get access to the D3.js library so that we can begin. In this case, we'll be including the library using the HTML <script>
tag.
<script src="https://d3js.org/d3.v7.js"></script>
Introduction
We've already had a look at how to draw SVG shapes with D3.js, but we may often find ourselves wanting to animate these shapes to bring them to life! We can achieve animation using transitions in D3.js1, which enables key-frame animations consisting of two key-frames: start and end. Let's demonstrate a transition by gradually increasing the radius of the below circle, making it appear as if it's growing.
<svg>
<circle cx="150" cy="75" r="50"></circle>
</svg>
The above circle is positioned at
<svg>
<circle cx="150" cy="75" r="75"></circle>
</svg>
By the end of the transition, the circle will have a radius of
A Container for the Output
This is where you will see the output of the code cells that follow it, provided they are referencing the corresponding id
.
<div id="container"></div>
Note
The animation started on page load and lasted two seconds. If you missed it - you can refresh the page to see it in action again!
Creating an Empty SVG
We'll create a new detached <svg>
element and use the returned selection throughout the rest of this section.
svg = d3.create("svg");
Creating a Circle Element
Let's create our circle! We'll append the <circle>
element to our selection of the <svg>
element, and we'll use our starting coordinates
var circle = svg
.append("circle")
.attr("cx", 150)
.attr("cy", 75)
.attr("r", 50);
Animating the Circle Element
Much like d3.selection()
, d3.transition()
can be used to modify attributes and styles. The difference is that whilst d3.selection()
applies the changes instantly, d3.transition()
applies the changes gradually (and smoothly) over a specified duration.
Whilst we could use a d3.selection()
to change the radius of our circle from its current value of
circle.attr('r', 75);
We will instead be using a d3.transition()
to do the same, but over a duration of
circle
.transition()
.duration(2000)
.attr('r', 75);
We can see that we've invoked .transition()
on the selection of our <circle>
element, specified our transition duration with .duration()
, and specified r
as the transition to transition to a value of
Appending to the Container
Finally, let's append everything to our container.
d3
.select("#container")
.append(() => svg.node());
We can see the output by checking on our container with the corresponding id, which in this case is where id=container
.
Conclusion
If we inspect the HTML, we will see the <svg>
and <circle>
elements have been added to the <div>
where the id=container
. We can also see that the <circle>
element's r
attribute has been set to
<div id="container">
<svg>
<circle cx="150" cy="75" r="75"></circle>
</svg>
</div>