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
The W3C SVG specification defines several basic shape elements such as rect
, circle
, and ellipse
1. We can create these shape elements using SVG directly, for example with the following.
<svg>
<circle cx="50" cy="50" r="50"></circle>
</svg>
But we can also create these with D3.js. In this section, we'll use D3.js to output a circle identical to the one above.
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>
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
To create a <circle>
element with D3.js we can invoke the d3.append(name)
function on our svg
selection and pass in the name of the element. In this case, we're passing in circle
as our argument for the name
parameter. We'll also specify the following geometry properties2:
- the horizontal centre coordinate,
cx
; - the vertical centre coordinate,
cy
; - and the Radius,
r
.
svg
.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 50);
We'll come back to selections, d3.append(name)
, and attr()
in more detail in future sections.
We could do the same with other basic shape elements whilst specifying the appropriate geometry properties for each one. For example, the <rect>
element's geometry properties include the horizontal radius, rx
, and the vertical radius, ry
. These two properties can be used to round off corners, i.e. creating a rectangle with rounded corners. We can check this by using SVG directly:
<svg>
<rect x="100" y="25" width="100" height="100" rx="20" ry="20"></rect>
</svg>
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'll see the <svg>
element has been added to the <div>
where the id=container
.
<div id="container">
<svg>
<circle cx="50" cy="50" r="50"></circle>
</svg>
</div>
With this, we're now able to add basic SVG shape elements to the DOM using D3.js.