Element and 2D Context

The Canvas Element and 2D Context

A bare <canvas> is a transparent 300 x 150 bitmap; width and height size the bitmap and CSS only stretches it. Content between the tags is fallback for screen readers. getContext('2d', options) returns the same drawing object on every call. fillRect(), strokeRect() and clearRect() draw at once.

A first BookNest drawing with fallback contentHTMLLive
<canvas id="c" width="600" height="72" role="img" aria-label="The Quiet Harbor, a blue cover">
  The Quiet Harbor by Mara Ellison: a blue cover with a white title band.</canvas>
<script>
  const ctx = c.getContext('2d', { alpha: true });
  ctx.fillStyle = '#1f5f8b';  ctx.fillRect(4, 4, 48, 64);          // the cover
  ctx.clearRect(10, 14, 36, 10);  ctx.lineWidth = 2;  ctx.strokeRect(4, 4, 48, 64);
  ctx.font = 'bold 22px Georgia';  ctx.fillText('The Quiet Harbor', 66, 40);
</script>
Browser output of Listing 2.1
Browser output of 1

Options are fixed at creation: alpha: false promises an opaque canvas, colorSpace: 'display-p3' widens the gamut, and getContextAttributes() reports them. A canvas holding a 2D context returns null for 'webgl'. Interactive canvases also need focusable HTML controls (Mouse and Hit Testing).