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
