liveBook · Manning

Stroke

As explained in D3.js in Action, Third Edition

A stroke is the outline paint and width applied to the boundary of a Canvas shape.

A stroke draws a shape’s visible outline. In Canvas, calling stroke() renders the current path’s border; in SVG, the stroke attribute makes a line visible by giving it a color. A stroke is separate from a fill, which paints the shape’s interior. section 15.2.2 section 15.2.3 section 1.2.2

For a Canvas line, build the path first: beginPath() starts it, moveTo() places the drawing point, lineTo() extends the line, and stroke() outlines it. Think of stroke() as putting the pen mark onto the canvas after defining where that mark travels. section 15.2.2

Listing 15.5 Drawing a line (main.js)
context.beginPath();
context.moveTo(66, 60);
context.lineTo(186, 300);
context.stroke();

Follow the four commands in order to create a stroked Canvas line from one coordinate to another. section 15.2.2

Style and manage strokes deliberately:

  • Set context.strokeStyle before stroke() to choose a Canvas border color. The default Canvas color is black. section 15.2.3
  • Call beginPath() before starting a separately styled shape. Otherwise, earlier paths can receive the current stroke style. section 15.2.3
  • Batch shapes that share styles, then update fillStyle or strokeStyle when switching colors. section 15.2.3
  • In SVG, use stroke for color and stroke-width for outline width; an omitted stroke-width defaults to 1 px. section 1.2.2

Outlined rectangle and data circles

Use a transparent fill with a colored stroke to make a rectangle read as an outline. In a Canvas visualization, circles can combine fillStyle for a category color with strokeStyle for a border that represents another property, then render both with fill() and stroke(). section 1.2.2 section 15.3

Practice by drawing a centered square with a transparent fill and a 3 px black stroke, then add two diagonal black lines with the same stroke width. This makes outline styling part of a responsive Canvas graphic rather than an isolated API call. section 15.2.6

How D3.js in Action, Third Edition covers it

How deep it goes
Walks through Canvas path commands and styling, while SVG adds stroke color and width attributes.
Examples
Demonstrates a Canvas line, outlined rectangles, SVG lines, and circles encoding painting properties.
What it assumes
Teaches stroke from basic shape and coordinate commands without assuming prior SVG or Canvas knowledge.
What you can do after
Apply it via Canvas and SVG APIs to render and style shape outlines.
How it connects
Connects stroke to Canvas paths, fill, strokeStyle, SVG, and stroke-width.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.