liveBook · Manning

beginPath()

As explained in D3.js in Action, Third Edition

The Canvas beginPath() method starts a new path and clears the set of subpaths used by subsequent drawing operations.

Canvas beginPath() starts a new path and clears the subpaths accumulated by earlier drawing commands. Call it before defining an independent shape so later strokes and fills do not reuse previous geometry or receive unintended styles. section 15.2.2 section 15.2.3

Use beginPath() as the first step in each independent Canvas shape sequence:

Drawing separate shapes

context.beginPath(); context.arc(706, 106, 66, 0, 2 * Math.PI); context.stroke(); context.beginPath(); context.ellipse(706, 273, 66, 40, 0, 0, 2 * Math.PI); context.fill(); The second beginPath() keeps the ellipse independent from the circle. section 15.2.4

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

Inspect the complete four-command sequence for drawing a line: beginPath(), moveTo(), lineTo(), and stroke(). section 15.2.2

How D3.js in Action, Third Edition covers it

How deep it goes
Explains path resetting through several shape examples, without descending into Canvas implementation internals.
Examples
Demonstrates beginPath() with a line, three rectangles, a circle, an ellipse, and painted circles in mixed SVG-Canvas rendering.
What it assumes
Builds from zero with moveTo(), lineTo(), shape commands, fill(), and stroke() while assuming no advanced rendering background.
What you can do after
Apply it via the Canvas 2D API to prevent earlier paths from affecting subsequent shapes and styles.
How it connects
Connects beginPath() with Canvas paths, moveTo(), lineTo(), rect(), arc(), ellipse(), fill(), and stroke().

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.