FriconiX
Free collection of beautiful vector icons for your web pages.

D3.js tutorial - Part 6 - Basic shapes

To draw a shape, simply append a new tag in the SVG container and specify the properties of the shape as attributes. Since the syntax for drawing shapes is always the same, we will not detail each. We'll just provide an example (source code and online example) for each shape; you'll easily figure out how it works.

Circle

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

Ellipse

var circle = svg.append("ellipse")
                .attr("cx", 150)
                .attr("cy", 100)
                .attr("rx", 20)
                .attr("ry", 60);  

Rectangle

var rectangle = svg.append("rect")
                    .attr("x", 10)
                    .attr("y", 40)
                    .attr("width", 50)
                    .attr("height", 100); 

Segment (or straight line)

var circle = svg.append("line")
                .attr("x1", 5)
                .attr("y1", 5)
                .attr("x2", 100)
                .attr("y2", 50)
                .attr("stroke-width", 2)
                .attr("stroke", "black");    

Text

var circle = svg.append('text')
                .attr('x', 100)
                .attr('y', 50)
                .text("I'm a text with D3.js");

Polyline

var circle = svg.append('polyline')
                .attr('points', "50,50 100,50 100,100 150,100 200,150 250 150")
                .attr('fill', "none")
                .attr('stroke', 'blue');

Polygon

var circle = svg.append('polygon')
                .attr('points', "50,50 200,50 250,100 250,150 20,50")
                .attr('stroke', '#f00')
                .attr('fill', 'none');

Filled polygon

var circle = svg.append('polygon')
                .attr('points', "50,50 200,50 250,100 250,150 20,50")
                .attr('fill', 'green');

See also


Last update : 01/28/2020