liveBook · Manning

getContext()

As explained in D3.js in Action, Third Edition

getContext() is a Canvas method that returns a rendering context for a specified drawing mode.

getContext() returns a Canvas rendering context for a specified drawing mode. Calling canvasElement.getContext("2d") provides the 2D context used for drawing. section 15.3

Initialize the context when the canvas is ready:

  • Bind the canvas node to canvasElement. section 15.3
  • Call getContext("2d") inside onMount(), after the node enters the DOM. section 15.3
  • Scale the context by window.devicePixelRatio when the canvas uses a resolution-corrected size. section 15.3

Canvas circles over SVG

A mixed-mode visualization places Canvas above an SVG container. After getContext("2d") initializes the drawing context, code sets fillStyle and strokeStyle, begins paths, draws arcs, and fills and strokes painting circles. section 15.3

Figure 15.11 Adopting the mixed-mode rendering approach, we use an SVG container to display the axes, drawings, and letters, and we add a canvas element on top that renders the painting circles.
figure

See how the Canvas layer complements SVG by rendering the painting circles. section 15.3

How D3.js in Action, Third Edition covers it

How deep it goes
Explains DOM-timed initialization and resolution scaling, then applies the context to circle drawing.
Examples
Uses a Canvas layer to render colored, bordered painting circles over an SVG visualization.
What it assumes
Assumes a canvas element and Svelte’s DOM binding and lifecycle mechanisms.
What you can do after
Build a 2D Canvas drawing layer and render shapes after the element mounts.
How it connects
Connects Canvas with SVG, Svelte, onMount(), devicePixelRatio, and force simulation.

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.