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

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.

主站蜘蛛池模板: 逊克县| 洪江市| 依安县| 固始县| 会宁县| 灵寿县| 玉树县| 富顺县| 绥棱县| 克拉玛依市| 若羌县| 谢通门县| 胶州市| 塔城市| 光泽县| 汉寿县| 清水河县| 宜川县| 怀远县| 独山县| 响水县| 施秉县| 黄梅县| 弥勒县| 卢湾区| 三穗县| 新河县| 乐清市| 澄江县| 乐亭县| 新乐市| 筠连县| 昌吉市| 航空| 启东市| 盐源县| 绥德县| 贡嘎县| 万山特区| 德阳市| 五莲县|