Drawing with SVG

To draw with D3, you can add shapes manually by defining the appropriate SVG elements, or you can use helper functions that help you create advanced shapes easily.

Most of what we'll be doing in the rest of this book uses SVG. Pay attention, because this is all going to become very familiar, very quickly.

There's a bunch of stuff that is common to most D3 charts, and we're going to start off by saving ourselves a boatload of time by creating a new factory function that sets everything up for us all. Create a new folder called common/ inside lib/ and create a new file called index.js in that folder. Add the following to the file to import D3:

import * as d3 from 'd3';

We will set up a prototype that we can override later if we need to:

const protoChart = { 
width: window.innerWidth,
height: window.innerHeight,
margin: {
left: 10,
right: 10,
top: 10,
bottom: 10,
},
};

This is just a plain old object with a bunch of values we'll use later on--consistent 10 pixel margin on each side, with width and height set to the interior dimensions of the browser window.

Next, we will create a factory that returns a basic chart, using the values used in the preceding code and allowing them to be overridden, as necessary:

export default function chartFactory(opts, proto = protoChart) { 
const chart = Object.assign({}, proto, opts);

chart.svg = d3.select('body')
.append('svg')
.attr('id', chart.id || 'chart')
.attr('width', chart.width - chart.margin.right)
.attr('height', chart.height - chart.margin.bottom);

chart.container = chart.svg.append('g')
.attr('id', 'container')
.attr('transform', `translate(${chart.margin.left}, ${chart.margin.top})`);

return chart;
}

Here, we assign our protoChart object from before as the default value of the proto function argument. In this way, we can either override individual properties in the first argument or supply a whole new prototype, if we need to do something really funky. We then use d3-selection to add an SVG element to the page body, use our width, height, and margin values to size that appropriately and get bottom/right margins, and then add a group element g that we shift right and down in order to get our top/left margins.

It's simple, but it will do a lot of heavy lifting for us over the next few chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset