CodeBlanks Logo Icon CodeBlanks

The canvas element

JavaScript course · Expert · Lesson 42/63

Learn the canvas element and how to get its 2D drawing context.

The canvas element

Canvas is an HTML element that lets you draw pixel-based graphics with JavaScript. A canvas tag stands in for the surface; its width and height attributes set the size.

To draw, you first select the element, then call getContext('2d') to get the two-dimensional drawing context. On this context you can draw rectangles, lines, arcs and text, and set colors. All drawing methods run through this context.

Getting the context

Drawing on a canvas takes two steps. First select the element with document.getElementById, then get the drawing context with getContext('2d').

The context holds the drawing methods and the drawing state (color, line width). It is usually assigned to a variable named ctx. Without the context the canvas stays an empty rectangle; all drawing happens on this context.

Exercise Get canvas and context

Select the canvas element with document.getElementById('canvas'), get its 2D drawing context with getContext('2d'), and log the context with console.log. Assign the context to a variable named ctx.

Show example solution
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
console.log(ctx);

Test yourself

  1. Which call returns the 2D drawing context?

    const canvas = document.getElementById('canvas');
    • canvas.getContext('canvas')
    • canvas.getContext('2d')
    • canvas.getContext('webgl')
    • canvas.getContext('drawing')
    Show answer

    canvas.getContext('2d') — Correct! The '2d' argument returns the two-dimensional drawing context.

  2. Get the context

    const canvas = document.getElementById('canvas');
    const ctx = canvas.____('2d');
    Show answer
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
  3. Match the canvas terms

    canvas
    HTML element
    getContext
    get context
    '2d'
    two-dimensional
    ctx
    drawing context

All lessons in Expert