Drawing svg shapes with D3 is described in this javascript d3 introduction tutorial.
D3 stands for Data Driven Documents.
To use d3.js you will need to link with the d3.js library. The current D3 CDN (Content Delivery Network) is as follows:

The link to the github D3 repository will also allow you to download the latest version of D3.

Our first example will be to create a basic svg (scalable vector graphic) shape using the D3 library. D3 is mainly used for graphs and charts which use svg shapes so learning how to draw svg shapes is a good place to start.
First of all here is a (100px * 100px) blue square.

See the Pen D3SquareFirstPen by Daniel (@Parsons) on CodePen.

The six lines of code can be broken down to explain matters better.

  1. d3.select(‘#svgSquare’) – Selects the element with an ID of ‘svgSquare’. Works like getElementById in javascript.
  2. .append(‘svg’). Appends a ‘svg’ element to the ‘#svgSquare’ element.
  3. .append(‘rect’). Appends a ‘rect’ element to the ‘svg’ element.
  4. .attr(‘width’,100) – Attaches a ‘width’ attribute with the value of ‘100’ pixels to the ‘rect’ attribute.
  5. .attr(‘height’,100). Attaches a ‘height’ attribute with the value of ‘100’ pixels to the ‘rect’ attribute.
  6. .style(‘fill’,’#31708f’). Attaches a style attribute with the ‘fill’ hexadecimal value of ‘#317084’.

Each line is joined by the dot. This method is called chaining and is the syntax method used a lot in D3.

To move the square two more attributes are added. A ‘x’ attribute to move the square along the x-Axis and a ‘y’ attribute to move the square along the y-Axis.

See the Pen svgSquareSecondPenMoveIt by Daniel (@Parsons) on CodePen.

The square has been moved 50 pixels across and 50 pixels down.

Next on lines 3,4 and 5 three new attributes are added to create a background.

See the Pen svgSquareThirdBackgroundAdd by Daniel (@Parsons) on CodePen.

On line 3 the ‘width’ attribute with a value of ‘200’ pixels is attached to the ‘svg’ element. The ‘height’ attribute with a value of ‘200’ pixels on line 4 is also attached to the ‘svg’ element as is the ‘style’ attribute with a ‘background’ hexadecimal value of ‘#d9edf7’ on line 5.

Here is a screenshot of the DOM (Document Object Model) that shows how D3 manipulates the DOM to create svg shapes.

Javascript D3 Introduction Tutorial
D3 manipulating the DOM.

And finally lets invert the ‘fill’ and ‘background’ colours for affect.

See the Pen D3scriptCdn by Daniel (@Parsons) on CodePen.


More on D3 (Data Driven Documents)

D3 logo

SVG logo.

Share!Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *