000 Introduction SVG and D3

A polygon is a svg element that defines a graphic shape delimited by at least three sides. In order to generate a polygon we must provide an array containing the values needed to locate in an x and y coordinate system, each corner of the polygon. Each corner, therefore takes an array of two values, one for the x coordinate, and another for the y coordinate. These array of values must be provided inside the attribute “points” as in the following syntax:

<polygon points="135,5 70,115 5,5" style="fill:#F95837;" />

The result of the previous example would look like the followin graphic:

D3.js is a javascript library that allowes the generation of elements in the DOM, binded to data input values. These elements are generated dynamically in the client which means that any update of the DOM tree, will also be processed by the client, avoiding the need of submitting requests to the server, which adds considerable amounts of latency and increases the amount of data being transfered during the connection by forcing new page reloads.

In order, to generate the previous polygon dynamically with D3.js we must bind some data to the polygon element, that will be needed when defining the polygon’s attributes. Reviewing the previous: we have said that a polygon is a svg element that takes an atrribute “points” which must contain an array of at least three values separated from each other by a space, each of these three values takes an array of two values, both of them provide the position of a corner of the polygon in a x and y coordinate system. The first value provides the coordinate that sets the position of the corner in the x axis, and separated from the first by a comma, the second value provides the coordinate that sets the position of the corner in the y axis.

We could provide those coordinates using the following dataset:

var dataset = [
	[
		[ 135,   5 ],
		[ 70,  115 ],
		[ 5,     5 ]
	]
];

So the final D3.js script would look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
var svg = d3.select("body").append("svg").attr({
	width: 838,
	height:160
});

var dataset = [
	[
		[ 135,   5 ],
		[ 70,  115 ],
		[ 5,     5 ]
	]
];

var polygon = svg.selectAll("polygon")
	.data(dataset).enter()
	.append("polygon");

polygon.attr({
	points: function(d){ return d; },
	fill: "#F95837"
});

Checkout the code in line 19.