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
The W3C SVG specification defines several basic shape elements such as
ellipse1. 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
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,
- the vertical centre coordinate,
- and the Radius,
svg .append("circle") .attr("cx", 50) .attr("cy", 50) .attr("r", 50);
We'll come back to selections,
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
If we inspect the HTML, we'll see the
<svg> element has been added to the
<div> where the
<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.