Line

Making a straight line with D3

Using a traditional straight edge we line up two points, keep our hands steady, and follow that edge with a writing tool.

Using software, we can be far more precise. We can directly connect the two points without having to account for the width of the writing tool, the gap from the straight edge, or our imperfect grasp on the tools as we follow to create the line.

Following the principles of simplicity, we’re going to focus first on lines that go through two points; A and B

var myLine = drawing.append("svg:line")
    .attr("x1", A.attr("cx"))
    .attr("y1", A.attr("cy"))
    .attr("x2", B.attr("cx"))
    .attr("y2", B.attr("cy"))
    .style("stroke", "rgb(33,150,243)");

Let’s run through the above:

var myLine

We’re creating a variable that we can refer to later as “myLine”. This could be labelled anything, or we could drop the variable all together. The line would still be drawn.

drawing.append

We’re adding to the D3 drawing we’ve created already. Knowing that we’re appending is important, as this tells us the order that lines are drawn.

("svg:line")

The method that we’re using is SVG’s line function[1]. D3.js allows us direct access to SVG’s built-in functions, and this makes it easier to do things SVG is good at.

    .attr("x1", A.attr("cx"))
    .attr("y1", A.attr("cy"))
    .attr("x2", B.attr("cx"))
    .attr("y2", B.attr("cy"))
    .style("stroke", "rgb(33,150,243)");

In this section, we’re adding the attributes svg:line needs to make a line: one point to start from (x1, y1), and one point to end at (x2, y2).

Since we created the points A and B with D3 attributes like so:

    .attr("cx", centreX)
    .attr("cy", centreY)

We can access those same attributes by using

    point.attr("cx")
    point.attr("cy")

Which leads us to

    .attr("x1", A.attr("cx"))
    .attr("y1", A.attr("cy"))

We also need to tell svg:line that we want to draw (or “stroke”) this line, and what colour to make it. We do this with .style.