官术网_书友最值得收藏!

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 inpidual 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.

主站蜘蛛池模板: 锡林浩特市| 越西县| 教育| 皮山县| 象山县| 新化县| 读书| 漳平市| 台江县| 新闻| 南开区| 邯郸县| 土默特右旗| 夏河县| 彩票| 乌海市| 巴彦县| 赣榆县| 肇州县| 江达县| 博爱县| 五常市| 壶关县| 滕州市| 永定县| 马公市| 通渭县| 含山县| 南京市| 临夏市| 鹤山市| 陵川县| 阳朔县| 卓资县| 珠海市| 金秀| 襄樊市| 格尔木市| 花莲县| 铜陵市| 镇坪县|