CHAPTER 49 · HTML

Canvas drawing: use a script and keep a text equivalent

Create a small bitmap drawing and a button-driven comparison. Understand the drawing surface, coordinates and the limits of fallback content.

Download example files (ZIP)

An empty drawing sheet on the page

Imagine a small sheet on which you paint shapes. Canvas supplies a drawing surface. HTML establishes the element and dimensions; JavaScript issues the drawing commands. Adding a canvas element alone does not draw a chart, photograph or line.

The result is a bitmap: a grid of pixels, tiny points of colour. Unlike SVG shapes, the painted rectangles are not separate rect elements that you can locate in the document. Choose ordinary HTML for information and SVG for simple document-based diagrams when they better suit the task.

Width and height define the bitmap

Give canvas an id and explicit width and height attributes. Our first example uses 320 by 160 drawing pixels. A canvas requires a closing tag; fallback content can go between its tags. Without these attributes, its default drawing dimensions are 300 by 150.

CSS can change the displayed size, but stretching the same bitmap can blur or distort it. Our CSS lets the display shrink proportionally on a small screen. High-density displays may need more detailed bitmap sizing in a full graphics application; this small example deliberately keeps the coordinate system simple.

Ask for a drawing context

GetElementById finds the canvas. GetContext("2d") asks for its two-dimensional drawing interface, called a context. If no suitable context is available, the result can be null. The if (context) block runs drawing instructions only when one exists.

The script follows the canvas so the element is present when looked up. It does not need a remote library, network service or image download. Save the whole HTML example to run it, because scripts stay disabled in the tutorial preview.

Read each rectangle command

FillStyle sets the paint for later fills. FillRect(x, y, width, height) paints a filled rectangle. The first example draws blue at 25,45 with width 110 and height 60, then orange at 190,25 with width 80 and height 110.

Coordinates start at the upper-left by default. X increases rightward and y downward. Setting a new fillStyle changes future fills, not rectangles already painted. Choose positions that fit within the bitmap dimensions.

Redrawing means issuing commands again

The second example draws only after activating its native button. ClearRect(0,0,canvas.width,canvas.height) clears the drawing bitmap, then the commands repaint the bars. Group A is 90 units wide and Group B 150, using 30 units per item for counts 3 and 5.

Each repeat draws the same fictional data. It does not fetch new figures or record a user score. Changing the canvas width or height attribute resets the bitmap and drawing state even if the new value matches the old one. Plan size changes before painting, or redraw afterwards.

Do not rely only on canvas fallback text

Text between canvas tags is fallback for environments that do not support canvas. It is not guaranteed to appear when a supported canvas stays blank because its script failed or scripting is disabled.

Keep the explanation and meaningful data outside canvas as normal visible text. Our comparison lists both counts in HTML. Aria-labelledby gives the canvas a name referring to that explanation; it does not turn painted shapes into separately navigable data. Do not put essential form controls or the only chart values inside a bitmap.

A picture still needs a truthful explanation

The drawing-state paragraph reports whether the requested drawing action succeeded. Aria-live=polite supports announcing its changed sentence without moving focus. The static counts stay readable even if no drawing is possible.

In our isolated preview the canvas remains unpainted and a clear notice explains why. The code box is still complete. Students should test drawing in the saved file rather than concluding that a preview restriction is a drawing bug.

Canvas and SVG solve different problems

SVG retains shape elements in the document and is useful for scalable diagrams. Canvas paints pixels through commands and can suit repeated redraws, games or image processing. Neither automatically makes an accessible interactive chart. Consider ordinary text and tables for values people need to compare, copy or understand with assistive tools.

Our two programs introduce the HTML surface and small drawing commands. Animation loops, hit testing, image loading and high-density resizing belong to a later JavaScript or graphics lesson, not hidden unexplained code in this beginner chapter.

Follow the idea

Paint and explain
  1. 1Canvas: the bitmap surface
  2. 2Context: the drawing interface
  3. 3Commands: paint or clear pixels
  4. 4HTML: keep the important values readable

Canvas fallback is not a universal script-failure message.

Complete program: canvas-rectangles.html

Save this as canvas-rectangles.html. Open it in your browser.

canvas-rectangles.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Draw on a Canvas</title>

    <style>
      canvas {
        max-width: 100%;
        height: auto;
        border: 1px solid #777;
      }
    </style>
  </head>
  <body>
    <h1>Paint two practice rectangles</h1>
    <main>
      <p id="drawing-description">
        A blue rectangle sits to the left of a taller orange rectangle. The colours carry no
        ranking.
      </p>
      <canvas
        id="practice-canvas"
        width="320"
        height="160"
        role="img"
        aria-labelledby="drawing-description"
        >Two rectangles: a blue one on the left and a taller orange one on the right.</canvas
      >
      <p>The drawing is created by JavaScript when this saved page runs.</p>
      <script>
        const canvas = document.getElementById('practice-canvas');
        const context = canvas.getContext('2d');
        if (context) {
          context.fillStyle = '#2458a6';
          context.fillRect(25, 45, 110, 60);
          context.fillStyle = '#b85c15';
          context.fillRect(190, 25, 80, 110);
        }
      </script>
    </main>
  </body>
</html>
Browser previewDocument title: Draw on a Canvas

This preview shows the example in a browser. Save the complete code in local files to test links between pages and downloads. Same-page section links work here. JavaScript does not run in this preview. Save the complete example and any named script file together to test its actions or canvas drawing in your browser.

Expected result in a saved browser page: a blue rectangle on the left and a taller orange rectangle on the right, surrounded by a border. The visible explanation remains even if the drawing does not run. The tutorial preview intentionally leaves the canvas unpainted because scripts are disabled.

Complete program: canvas-comparison.html

Save this as canvas-comparison.html. Open it in your browser.

canvas-comparison.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>A Canvas with a Text Equivalent</title>

    <style>
      canvas {
        max-width: 100%;
        height: auto;
        border: 1px solid #777;
      }
    </style>
  </head>
  <body>
    <h1>Draw a fictional item comparison</h1>
    <main>
      <p id="comparison-description">
        Group A has 3 items and Group B has 5 items. One item is drawn as 30 horizontal canvas
        units.
      </p>
      <ul>
        <li>Group A: 3 items</li>
        <li>Group B: 5 items</li>
      </ul>
      <button type="button" id="draw-comparison">Draw the comparison</button>
      <p id="drawing-state" aria-live="polite">
        Activate the button to draw the bars in the saved page.
      </p>
      <canvas
        id="comparison-canvas"
        width="320"
        height="180"
        role="img"
        aria-labelledby="comparison-description"
        >Group A has 3 items. Group B has 5 items.</canvas
      >
      <script>
        const canvas = document.getElementById('comparison-canvas');
        const context = canvas.getContext('2d');
        const state = document.getElementById('drawing-state');
        document.getElementById('draw-comparison').addEventListener('click', function () {
          if (context) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.fillStyle = '#2458a6';
            context.fillRect(25, 35, 90, 35);
            context.fillStyle = '#b85c15';
            context.fillRect(25, 110, 150, 35);
            state.textContent = 'Drawing shown. Group A has 3 items; Group B has 5 items.';
          } else {
            state.textContent = 'Drawing is unavailable. Read the item counts above.';
          }
        });
      </script>
    </main>
  </body>
</html>
Browser previewDocument title: A Canvas with a Text Equivalent

This preview shows the example in a browser. Save the complete code in local files to test links between pages and downloads. Same-page section links work here. JavaScript does not run in this preview. Save the complete example and any named script file together to test its actions or canvas drawing in your browser.

Expected result: the counts are always readable as ordinary text. Activate Draw the comparison in the saved page to paint bars of widths 90 and 150 and update the state sentence. Repeated activation clears and redraws the same values, rather than adding more items.

Problem and solution

Problem: a supported canvas remains blank after JavaScript fails, but the author expects its inner text to appear.

Solution: keep the essential explanation outside canvas and investigate the script separately. Unsupported-element fallback is not a universal script-failure message.

Common mistakes and useful tips

  • Do not expect canvas markup to draw by itself.
  • Separate bitmap dimensions from CSS display size.
  • Check getContext before using it.
  • Changing dimensions clears the bitmap and drawing state.
  • Keep essential values in ordinary HTML too.
  • Do not describe static fictional bars as live measurements.

Practice questions

  1. What does canvas provide before drawing commands run?
  2. What are the arguments of fillRect?
  3. Does changing fillStyle recolour existing rectangles?
  4. How wide is the Group B bar and why?
  5. Will inner canvas text necessarily appear when a script fails?
  6. Save the comparison program, activate it twice and inspect the text and bars. What stays the same?
Check your practice answers
  1. A drawing surface, initially unpainted.
  2. X position, y position, width and height.
  3. No. It affects subsequent fills.
  4. 150 drawing units: 5 items times 30 units per item.
  5. No. Keep important content outside the canvas.
  6. The counts remain 3 and 5; the bars are cleared and redrawn with the same widths. No new data is fetched or counted.

Interview questions

How does canvas differ from SVG?

Canvas paints a bitmap through drawing commands. SVG retains vector shape elements in the document. Choose according to the job and provide accessible meaning either way.

Why set width and height attributes?

They define the drawing bitmap. CSS resizing alone changes display size and can stretch the existing pixels.

What happens when canvas dimensions are reset?

The bitmap and drawing state are cleared, so an application must redraw what it still needs.

Why keep chart values in HTML?

Painted pixels are not ordinary selectable or structurally meaningful data. Visible text or a table makes the actual values available independently of the drawing.

Quick revision

  • Create the surface, then draw.
  • Read coordinates and dimensions carefully.
  • Keep text equivalents outside canvas.
  • Test saved scripts and avoid false live-data claims.