d3(1) Basics
- SVG: Scalable Vector Graphics
1 | <!-- using an img tag --> |
- In HTML file
1 | <svg width="600" height="600"> |
- SVG Paths
1 | <path d="M150 0 L75 200 L225 200 Z" fill="orange"/> |
- M - moveto. The starting point
- L - lineto. Draw line to a certain point
- Z - closepath
- H/V - Horizontal/Vertical lineto
- C - Curveto
- S - Smooth curveto
D3 basics
Select an item
const d = d3.select('div');
Select all items
d3.selectAll('div');
Append tags to a container
1
2const svg = canvas.append('svg');
svg.append('rect');Method chainning & attributes
1
2svg.attr('height', 600);
svg.append('rect').attr('height', 300).attr('width', 300);Text element
1
2
3
4
5
6svg.append('text');
.attr('x', 20)
.attr('y', 200)
.attr('fill', blue)
.text('hello world!')
.style('font-family', 'arial')Groups
1
const group = svg.append('g');
Data with D3
Example without database
1
2
3
4
5
6
7
8
9
10const data = [
{width: 200, height: 100, fill: 'purple'}
];
const svg = d3.select('svg');
const rect = svg.select('rect')
.data(data)
.attr('width', (d, i, n) => d.width)
.attr('height', d => d.height)
.attr('fill', d => d.fill);For multiple elements, data with multiple entries will apply to each element automatically
If the data retrieved from database has more entries than the hard-coded DOM, then
1
2
3
4
5
6const rects = d3.selectAll('rect')
.data(data)
rects.enter()
.append('rect')
.attr()Data with JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19const svg = d3.select('svg');
d3.json('planets.json').then(data => {
const circs = svg.selectAll('circle') // though there is no circle in the DOM
.data(data); // bind the data to the invisible entries
// add attrs to circs already in the DOM
circs.attr('cy', 200)
.attr('cx', d => d.distance)
.attr('r', d => d.radius)
.attr('fill', d => d.fill)
// append the enter selection to the DOM
circs.enter()
.append('circle')
.attr('cx', d => d.distance)
.attr('r', d => d.radius)
.attr('fill', d => d.fill)
})