Text

As mentioned, text is the only SVG shape that isn't really a path. Let's look at it first, so the rest of this chapter is about shapes. Add the following to the top of chapter2/index.js:

import * as d3 from 'd3'; 
import chartFactory from '../common/index';

Then, create a new function below our trusty old lifeExpectancyTable function:

export async function renderSVGStuff() { 
const chart = chartFactory();
const text = chart.container.append('text')
.text("Ceci n'est pas un trajet!")
.attr('x', 50)
.attr('y', 200)
.attr('text-anchor', 'start');
}

We took our chartFactory function and used it to create a new chart. We then appended a text element to the container property, which corresponds to our group element with all the margins. Then, we defined its actual text and added some attributes to position the text at the (x, y) point while anchoring the text at the start of a line.

The text-anchor attribute defines the horizontal positioning of the rendered text in relation to the anchor point defined by (x, y). The positions it understands are the start, the middle, and the end.
We can also fine-tune the text's position with an offset defined by the dx and dy attributes. This is especially handy when we adjust the text margin and baseline relative to the font size because it understands the em unit.

We now need to go back to lib/index.js and import our new function. Replace the first import statement in lib/main.js with this:

import './chapter2/index';

Then, add this at the end of chapter2/index.js:

renderSVGStuff();

Then, check it out:

Since we instantiated our function in chapter2/index.js, all we need to do is import it in lib/main.js, and it will run. The rest of these SVG examples will simply be appended to renderSVGStuff so that we can focus on using D3 and not just write JavaScript enclosures all day. We're not really making anything useful in this chapter, you can disregard what I said earlier about modularity until the end of this section.

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

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