Tutorials JavaScript Canvas API
Ch 61 / 78
Chapter 61 Advanced 20 min read JavaScript

JavaScript Canvas API

The HTML5 Canvas API gives you a pixel-level drawing surface directly inside the browser — draw shapes, gradients, images, and animate everything with requestAnimationFrame, all with zero external libraries required.

What you'll learn
What the Canvas API is and when to use it
Setting up <canvas> and getContext("2d")
Drawing rectangles, paths, and arcs
Applying colours, gradients, and shadows
Rendering text and images on canvas
Smooth animations with requestAnimationFrame

What Is the Canvas API?

The Canvas API is a browser-native 2D drawing interface that lets JavaScript render graphics directly onto a <canvas> HTML element. Unlike SVG (which uses XML markup), canvas is pixel-based — you issue drawing commands and the browser rasterises them immediately.

Canvas excels at:

2D Games
Sprite rendering, tile maps, collision detection — canvas is the go-to surface for browser-based 2D game engines.
Data Visualisation
Custom charts, heat-maps, and real-time dashboards. Libraries like Chart.js are built entirely on the Canvas API.
Image Processing
Read and manipulate individual pixels — apply filters, crop, resize, and export images client-side without a server.
Animations
Smooth 60 fps animations with requestAnimationFrame — particles, physics simulations, and interactive UI effects.
Canvas vs SVG
Use Canvas for high-performance pixel drawing, games, and real-time updates. Use SVG for scalable icons, interactive diagrams, and elements that need DOM-level event handling and accessibility. Both coexist in the same page.

Setting Up the Canvas Element

Add a <canvas> element in HTML, set its width and height attributes (not CSS — CSS only stretches the element, it doesn't change the drawing resolution), then get the 2D rendering context in JavaScript.

HTML — Canvas Element
<!-- Always set width/height as HTML attributes, NOT only in CSS -->
<canvas id="myCanvas" width="600" height="400">
  Your browser does not support the Canvas element.
</canvas>
JavaScript — Get Context
const canvas = document.getElementById("myCanvas");

// Feature detection
if (!canvas.getContext) {
  console.warn("Canvas not supported");
} else {
  const ctx = canvas.getContext("2d");   // ← 2D context object
  console.log(ctx);  // CanvasRenderingContext2D
}
Context Type Description
"2d" 2D drawing context — shapes, text, images, gradients (this chapter)
"webgl" WebGL 1.0 — hardware-accelerated 3D graphics using OpenGL ES 2.0
"webgl2" WebGL 2.0 — OpenGL ES 3.0 features, better performance
"bitmaprenderer" Replaces canvas contents with an ImageBitmap object
DPI / Retina Tip
On high-DPI screens (devicePixelRatio > 1), scale the canvas buffer to avoid blurry output: set canvas.width = cssWidth * devicePixelRatio, then call ctx.scale(devicePixelRatio, devicePixelRatio).

Drawing Rectangles

Rectangles are the only primitive that the 2D context can draw directly — no path needed. Three methods cover all rectangle operations:

Method Parameters What it does
fillRect() x, y, w, h Draws a filled rectangle using fillStyle
strokeRect() x, y, w, h Draws only the outline using strokeStyle
clearRect() x, y, w, h Erases pixels, making the region transparent
JavaScript — Rectangles
const canvas = document.getElementById("myCanvas");
const ctx    = canvas.getContext("2d");

// Filled rectangle
ctx.fillStyle = "#f7df1e";
ctx.fillRect(20, 20, 150, 80);       // x, y, width, height

// Outlined rectangle
ctx.strokeStyle = "#10b981";
ctx.lineWidth   = 3;
ctx.strokeRect(200, 20, 150, 80);

// Clear a punch-out hole inside the yellow rectangle
ctx.clearRect(50, 40, 60, 40);

Drawing Paths, Lines & Circles

Most complex shapes are built using paths. A path is a sequence of points connected by line segments, arcs, or curves. You open a path with beginPath(), describe the shape, then either stroke() or fill() it.

JavaScript — Lines
const ctx = canvas.getContext("2d");

ctx.beginPath();              // start a new path
ctx.moveTo(50, 50);           // lift pen, move to (50, 50)
ctx.lineTo(200, 50);          // draw line to (200, 50)
ctx.lineTo(125, 150);         // draw line to (125, 150)
ctx.closePath();             // close path back to start point

ctx.fillStyle   = "rgba(247,223,30,0.25)";
ctx.fill();                   // fill the triangle

ctx.strokeStyle = "#f7df1e";
ctx.lineWidth   = 2;
ctx.stroke();                 // stroke the outline
JavaScript — Circles (arc)
// arc(x, y, radius, startAngle, endAngle, counterclockwise?)
// Angles in radians: 0 = 3 o'clock, Math.PI*2 = full circle

ctx.beginPath();
ctx.arc(150, 100, 60, 0, Math.PI * 2);  // full circle
ctx.fillStyle   = "#a855f7";
ctx.fill();

// Semi-circle (half arc)
ctx.beginPath();
ctx.arc(300, 100, 60, 0, Math.PI);      // half circle (bottom)
ctx.strokeStyle = "#10b981";
ctx.lineWidth   = 3;
ctx.stroke();

Colours, Gradients & Shadows

fillStyle and strokeStyle accept any CSS colour string, a CanvasGradient, or a CanvasPattern. Gradients come in two types — linear and radial.

JavaScript — Linear Gradient
// createLinearGradient(x0, y0, x1, y1)
const grad = ctx.createLinearGradient(0, 0, 400, 0);
grad.addColorStop(0,   "#f7df1e");   // start: JS yellow
grad.addColorStop(0.5, "#f97316");   // mid: orange
grad.addColorStop(1,   "#a855f7");   // end: purple

ctx.fillStyle = grad;
ctx.fillRect(0, 0, 400, 100);
JavaScript — Radial Gradient & Shadow
// Radial gradient — createRadialGradient(x0,y0,r0, x1,y1,r1)
const radial = ctx.createRadialGradient(200,100,10, 200,100,90);
radial.addColorStop(0, "#ffffff");
radial.addColorStop(1, "#a855f7");

ctx.fillStyle = radial;
ctx.fillRect(110, 10, 180, 180);

// Drop shadow
ctx.shadowColor   = "rgba(0,0,0,0.5)";
ctx.shadowBlur    = 15;
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;

ctx.fillStyle = "#f7df1e";
ctx.fillRect(320, 60, 100, 80);

// Reset shadow so it doesn't affect later draws
ctx.shadowColor = "transparent";
Advertisement

Drawing Text

The 2D context provides two main text methods: fillText() (solid text) and strokeText() (outlined text). Set the font property using the same shorthand as CSS font.

JavaScript — Text on Canvas
// font shorthand: "style weight size family"
ctx.font        = "bold 36px 'Segoe UI', sans-serif";
ctx.textAlign   = "center";      // left | center | right | start | end
ctx.textBaseline = "middle";      // top | middle | bottom | alphabetic

// Filled text
ctx.fillStyle = "#f7df1e";
ctx.fillText("Canvas API", 300, 80);       // text, x, y

// Outlined text
ctx.strokeStyle = "#a855f7";
ctx.lineWidth   = 1;
ctx.strokeText("Chapter 61", 300, 130);

// Measure text width before drawing
const metrics = ctx.measureText("Canvas API");
console.log(metrics.width);          // pixels wide at current font
Accessibility Note
Text drawn on canvas is not readable by screen readers. Always provide a text alternative via aria-label on the canvas element, or fall-back content between the opening and closing <canvas> tags.

Drawing Images

drawImage() accepts an HTMLImageElement, HTMLVideoElement, or another HTMLCanvasElement as its source — making it easy to composite, scale, and crop images programmatically.

JavaScript — drawImage() Overloads
const img = new Image();
img.src = "/images/photo.jpg";

img.onload = () => {
  // 3-arg: draw at (x, y) at natural size
  ctx.drawImage(img, 0, 0);

  // 5-arg: draw scaled to (dw × dh)
  ctx.drawImage(img, 0, 0, 200, 150);

  // 9-arg: crop (sx,sy,sw,sh) then draw at (dx,dy,dw,dh)
  ctx.drawImage(img,
    100, 50, 200, 150,   // source crop
    0,   0,  400, 300    // destination
  );
};

// Read pixel data after drawing
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// imageData.data — Uint8ClampedArray [R,G,B,A, R,G,B,A, ...]

Animations with requestAnimationFrame

The key pattern for smooth canvas animation is: clear → update state → draw → request next frame. requestAnimationFrame syncs drawing to the display refresh rate (typically 60 fps) and pauses when the tab is hidden.

JavaScript — Bouncing Ball Animation
const canvas = document.getElementById("myCanvas");
const ctx    = canvas.getContext("2d");

let ball = { x: 50, y: 50, r: 20, dx: 3, dy: 2 };

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

  // 2. Update state
  ball.x += ball.dx;
  ball.y += ball.dy;

  // Wall bounce
  if (ball.x + ball.r > canvas.width  || ball.x - ball.r < 0) ball.dx *= -1;
  if (ball.y + ball.r > canvas.height || ball.y - ball.r < 0) ball.dy *= -1;

  // 3. Draw
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);
  ctx.fillStyle = "#f7df1e";
  ctx.fill();

  // 4. Request next frame
  requestAnimationFrame(loop);
}

requestAnimationFrame(loop);   // kick off
Cancel the Loop
requestAnimationFrame returns a numeric ID. Store it and call cancelAnimationFrame(id) to stop the loop — essential in React useEffect cleanup or when navigating away.

Transformations — translate, rotate, scale

The 2D context has a transformation matrix that affects every subsequent draw call. Use save() / restore() to scope transformations to a single drawing operation without leaking state.

JavaScript — Rotate a Rectangle
// Save the untransformed state
ctx.save();

// Move origin to the center of the rectangle
ctx.translate(200, 100);

// Rotate 45 degrees (radians = degrees × π/180)
ctx.rotate(45 * Math.PI / 180);

// Draw centered on the origin (subtract half dimensions)
ctx.fillStyle = "#f7df1e";
ctx.fillRect(-60, -30, 120, 60);

// Restore — all future draws are unaffected by the rotation
ctx.restore();
Advertisement

Best Practices

⚡
Free Resource
Download our JavaScript Cheat Sheet
Canvas API, Geolocation, Web Workers, IndexedDB — all Web APIs on one page.
Get Sheet
✓ Do
  • Set width / height as HTML attributes, not only in CSS
  • Use save() / restore() to scope transformations
  • Cancel animation loops with cancelAnimationFrame(id) on cleanup
  • Reset shadowColor to "transparent" after shadow draws
  • Scale for devicePixelRatio on retina/HiDPI displays
  • Draw images inside the img.onload callback
✗ Don't
  • Forget beginPath() — old paths will be re-stroked accidentally
  • Set canvas size only via CSS — it stretches, creating blurry output
  • Call getContext() inside the animation loop — cache the context once
  • Leave a watchPosition or RAF loop running after navigation
  • Use canvas for text-heavy, accessible, or SEO-critical content
  • Forget to clear the canvas before every animation frame
Quick Check — Chapter 61

Which method must you call before drawing a new path to avoid re-drawing old paths?

Chapter Summary
  • The Canvas API lives on the <canvas> element — get its 2D context with canvas.getContext("2d").
  • Always set width and height as HTML attributes, not only via CSS.
  • Rectangles have three direct methods: fillRect(), strokeRect(), and clearRect().
  • Paths require beginPath() → describe shape → fill() / stroke().
  • fillStyle / strokeStyle accept CSS colours, CanvasGradient, or CanvasPattern.
  • Render text with fillText() / strokeText() — canvas text is not accessible to screen readers.
  • requestAnimationFrame(loop) drives smooth 60 fps animation — always clearRect at the start of each frame.
  • Scope transformations with save() / restore() to prevent state leaking between draw calls.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel