2 min read

Canvas API

The Canvas API provides a means for drawing graphics via JavaScript and the HTML <canvas> element. It can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

1. The <canvas> Element

First, you need a canvas element in your HTML.

<canvas id="myCanvas" width="500" height="300"></canvas>

2. The Rendering Context

To draw on the canvas, you need to get the "rendering context". The most common context is "2d".

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

3. Drawing Shapes (Rectangles)

The 2D context supports rectangles natively.

  • fillRect(x, y, width, height): Draws a filled rectangle.
  • strokeRect(x, y, width, height): Draws a rectangular outline.
  • clearRect(x, y, width, height): Clears the specified rectangular area (making it transparent).
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 150, 100);

ctx.strokeStyle = 'blue';
ctx.lineWidth = 5;
ctx.strokeRect(200, 10, 150, 100);

4. Drawing Paths

For other shapes, you use paths. A path is a list of points, connected by segments of lines that can be of different shapes, curved or not.

  1. beginPath(): Creates a new path.
  2. Path methods (moveTo, lineTo, arc, etc.).
  3. stroke() or fill(): Renders the path.
ctx.beginPath();
ctx.moveTo(50, 50);   // Start point
ctx.lineTo(100, 75);  // Line to...
ctx.lineTo(100, 25);  // Line to...
ctx.fill();           // Fills the triangle (automatically closes path)

Circles (Arcs)

arc(x, y, radius, startAngle, endAngle)

ctx.beginPath();
ctx.arc(200, 200, 40, 0, 2 * Math.PI); // Full circle
ctx.stroke();

5. Drawing Text

You can draw text directly onto the canvas.

ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello World', 10, 250);

ctx.strokeStyle = 'red';
ctx.strokeText('Hello World', 10, 290);

6. Drawing Images

You can draw images (HTMLImageElement, SVGImageElement, HTMLVideoElement, or HTMLCanvasElement) onto the canvas.

const img = new Image();
img.src = 'path/to/image.png';

img.onload = function() {
  // drawImage(image, x, y, width, height)
  ctx.drawImage(img, 0, 0, 100, 100);
};

7. Animation

To animate, you typically clear the canvas and redraw everything in a loop using requestAnimationFrame.

let x = 0;

function draw() {
  // 1. Clear
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 2. Update state
  x += 2;
  if (x > canvas.width) x = 0;

  // 3. Draw
  ctx.fillRect(x, 50, 50, 50);

  // 4. Loop
  requestAnimationFrame(draw);
}

draw();

8. Canvas vs. SVG

Feature Canvas SVG
Type Raster (Pixels) Vector (Shapes)
DOM Single DOM element Every shape is a DOM element
Events No event handlers on individual shapes Event handlers on every shape
Performance Better for many objects (thousands) Better for fewer objects, larger surface
Scaling Loses quality when zoomed Scales perfectly
Use Case Games, Pixel manipulation, High-frequency updates Charts, Icons, UI, Interactive maps

programming/javascript/vanilla/javascript programming/javascript/vanilla/dom-manipulation