TExcelTAD
Home › HTML › HTML Canvas

HTML Canvas

The <canvas> element is a blank rectangle of pixels that you paint on with JavaScript. It is perfect for charts, games, image filters, drawing apps and animations — anything where you want to control every pixel yourself.

Creating a canvas

html
<canvas id="myCanvas" width="300" height="150">
  Your browser does not support canvas.
</canvas>
  • width and height set the drawing resolution in pixels (default 300 × 150). Set them as attributes, not only with CSS, otherwise the drawing is stretched and blurry.
  • The text inside the element is a fallback shown only by browsers that can't display canvas.
  • By itself a canvas is invisible: it has no border and no content.

Getting the drawing context

To draw, you ask the canvas for a 2D context — an object full of drawing methods.

html · try it yourself
<canvas id="c" width="300" height="150" style="border:1px solid #999"></canvas>
<script>
  const canvas = document.getElementById('c');
  const ctx = canvas.getContext('2d');

  ctx.fillStyle = '#e34c26';          // fill colour
  ctx.fillRect(20, 20, 120, 80);      // x, y, width, height

  ctx.strokeStyle = '#264de4';        // outline colour
  ctx.lineWidth = 4;
  ctx.strokeRect(160, 40, 110, 80);
</script>

The coordinate system

The origin (0, 0) is the top-left corner. x grows to the right and y grows downward — the opposite of maths class.

Method / property What it does
fillStyle, strokeStyle Colour (or gradient) for fills and outlines
lineWidth Thickness of strokes
fillRect(x, y, w, h) Filled rectangle
strokeRect(x, y, w, h) Rectangle outline
clearRect(x, y, w, h) Erase an area to transparent
beginPath() Start a new shape
moveTo(x, y) / lineTo(x, y) Move the pen / draw a line
arc(x, y, r, start, end) Circle or arc (angles in radians)
closePath() Line back to the start of the shape
fill() / stroke() Paint the current path
font, fillText(text, x, y) Draw text
createLinearGradient(x0, y0, x1, y1) Make a colour gradient
drawImage(img, x, y) Draw an image or another canvas

Paths: lines, circles and shapes

Anything that isn't a rectangle is drawn as a path: start with beginPath(), describe the shape, then call fill() or stroke().

html · try it yourself
<canvas id="c" width="320" height="180" style="border:1px solid #999"></canvas>
<script>
  const ctx = document.getElementById('c').getContext('2d');

  // A triangle (mountain)
  ctx.beginPath();
  ctx.moveTo(20, 160);
  ctx.lineTo(110, 40);
  ctx.lineTo(200, 160);
  ctx.closePath();
  ctx.fillStyle = '#6a8f5a';
  ctx.fill();

  // The sun: a full circle is 0 to 2π radians
  ctx.beginPath();
  ctx.arc(260, 50, 28, 0, Math.PI * 2);
  ctx.fillStyle = 'gold';
  ctx.fill();

  // Ground line
  ctx.beginPath();
  ctx.moveTo(0, 160);
  ctx.lineTo(320, 160);
  ctx.strokeStyle = '#555';
  ctx.lineWidth = 3;
  ctx.stroke();
</script>

Text and gradients

html · try it yourself
<canvas id="c" width="340" height="120"></canvas>
<script>
  const ctx = document.getElementById('c').getContext('2d');

  const grad = ctx.createLinearGradient(0, 0, 340, 0);
  grad.addColorStop(0, '#e34c26');
  grad.addColorStop(1, '#f7b733');
  ctx.fillStyle = grad;
  ctx.fillRect(0, 0, 340, 120);

  ctx.font = 'bold 36px sans-serif';
  ctx.fillStyle = 'white';
  ctx.textAlign = 'center';
  ctx.fillText('Hello Canvas', 170, 72);
</script>

A tiny bar chart

Because you control every pixel, drawing a chart is just a loop:

html · try it yourself
<canvas id="chart" width="360" height="200" style="border:1px solid #ddd"></canvas>
<script>
  const data = [ ['Mon', 12], ['Tue', 19], ['Wed', 7], ['Thu', 15], ['Fri', 22] ];
  const ctx = document.getElementById('chart').getContext('2d');
  const max = 25, base = 175, barW = 44;

  ctx.font = '13px sans-serif';
  ctx.textAlign = 'center';
  data.forEach(([label, value], i) => {
    const x = 30 + i * 66;
    const h = (value / max) * 150;
    ctx.fillStyle = '#4a7bd0';
    ctx.fillRect(x, base - h, barW, h);
    ctx.fillStyle = '#222';
    ctx.fillText(value, x + barW / 2, base - h - 5);
    ctx.fillText(label, x + barW / 2, base + 16);
  });
</script>

Animation

To animate, clear the canvas and redraw each frame inside requestAnimationFrame, which calls your function about 60 times per second.

html · try it yourself
<canvas id="c" width="320" height="120" style="border:1px solid #999"></canvas>
<script>
  const ctx = document.getElementById('c').getContext('2d');
  let x = 30, dx = 2.5;
  function frame() {
    ctx.clearRect(0, 0, 320, 120);
    ctx.beginPath();
    ctx.arc(x, 60, 20, 0, Math.PI * 2);
    ctx.fillStyle = '#e34c26';
    ctx.fill();
    x += dx;
    if (x > 300 || x < 20) dx = -dx;   // bounce off the walls
    requestAnimationFrame(frame);
  }
  frame();
</script>

Note: A canvas is just pixels. Screen readers can't see what you drew, and the browser forgets the shapes once painted. Put important information in normal HTML too, or describe the canvas with fallback content or aria-label.

Tip: Canvas vs SVG: canvas is faster for thousands of moving objects (games, particles); SVG keeps every shape as an element you can style, click and scale without blur. You'll meet SVG in the next lesson.

Test yourself

Where is the point (0, 0) on a canvas?

  1. Center
  2. Bottom-left corner
  3. Top-left corner
  4. Top-right corner

What must you call to get the object with drawing methods?

  1. canvas.draw()
  2. canvas.getContext('2d')
  3. canvas.paint()
  4. document.context()

Why should you set width and height as attributes rather than only in CSS?

  1. CSS doesn't work on canvas
  2. The attributes set the pixel resolution; CSS alone stretches it and blurs the drawing
  3. Attributes load faster
  4. It is required for animation