D3.js tutorial - Part 5 - Create SVG and draw a circle

Create SVG

D3.js graphics is based on SVG (Scalable Vector Graphics). SVG is an XML-based vector image format with an open standard specifications. The basic idea is to add a SVG container (SVG tag) where the D3.js chart must be rendered. The graphics will later be insterted in this container. First, let's see how to append a SVG container in the document:

var svg = d3.select("body")
            .append("svg")
            .attr("width", 300)
            .attr("height", 200)
            .style('background-color', 'lightgrey')

Here is a live example:

Draw a circle

To draw a circle in the SVG container, simply add a <circle> tag inside the container and specify the circle properties as attributes:

//Draw the Circle
var circle = svg.append("circle")
                .attr("cx", 150)
                .attr("cy", 30)
                .attr("r", 20);

The previous code draw a circle with the following properties:

Here is our circle:

See also


Last update : 01/28/2020