Introduction & Setup

Grabbing a drawing surface from the DOM and preparing the 2 D context.

The <canvas> element provides a bitmap surface that you draw on using JavaScript. Everything rendered is immediate-mode; once a pixel is drawn it becomes part of the bitmap until manually cleared or over-painted.


<canvas id="stage" width="640" height="360"></canvas>
<script>
const canvas = document.getElementById("stage");
const ctx = canvas.getContext("2d");  // default = 2D context
</script>
		
Context TypeDescription / Use-case
"2d"Pixel-based 2 D API (paths, text, images).
"webgl"Low-level GPU (OpenGL ES 2.0).
"webgl2"OpenGL ES 3.0 core features.
"bitmaprenderer"Blit ImageBitmaps efficiently.
"webgpu"Modern GPU API (spec draft).

Canvas Coordinate System & State

Understanding pixels, saves, and resets.

  1. Origin is top-left (0 , 0); +x right, +y down.
  2. Canvas size is fixed pixels; CSS scales visually but does not add resolution.
  3. ctx.save() pushes the current transform, clip, and style; ctx.restore() pops it.

ctx.save();
ctx.translate(200, 150);
ctx.rotate(Math.PI / 4);
ctx.fillStyle = "crimson";
ctx.fillRect(-50, -50, 100, 100);
ctx.restore();
		

Drawing Primitives & Paths

Rectangles, lines, arcs, Béziers, and custom shapes.


ctx.fillRect(x, y, w, h);
ctx.clearRect(x, y, w, h);
ctx.strokeRect(x, y, w, h);

ctx.beginPath();
ctx.moveTo(50, 60);
ctx.lineTo(150, 60);
ctx.lineTo(100, 140);
ctx.closePath();
ctx.fill();          // uses current fillStyle

ctx.beginPath();
ctx.arc(250, 90, 40, 0, 2 * Math.PI);
ctx.strokeStyle = "steelblue";
ctx.lineWidth = 6;
ctx.stroke();
		

Path operations are accumulated; remember to call ctx.beginPath() for a fresh shape.

Colours, Gradients & Patterns

Creating fills and strokes beyond solid colors.


const grad = ctx.createLinearGradient(0, 0, 0, 200);
grad.addColorStop(0, "#ff9a9e");
grad.addColorStop(1, "#fad0c4");
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 200, 200);

const img = new Image();
img.src = "tiles.png";
img.onload = () => {
  const patt = ctx.createPattern(img, "repeat");
  ctx.fillStyle = patt;
  ctx.fillRect(220, 0, 200, 200);
};
		
  1. globalAlpha — uniform transparency (0 – 1).
  2. globalCompositeOperation — blend modes ("multiply", etc.).
  3. Line dash: setLineDash([5, 10]), lineDashOffset.

Text Rendering

Drawing dynamic text with styling.


ctx.font = "bold 32px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#fff";
ctx.fillText("Hello Canvas!", canvas.width/2, canvas.height/2);

ctx.strokeStyle = "#222";
ctx.lineWidth = 2;
ctx.strokeText("Outlines, too", 320, 300);
		

Measure before placement with ctx.measureText(text).width.

Images, Video & Spritesheets

Blitting external sources and cropping.


const hero = new Image();
hero.src = "sprite.png";
hero.onload = () => {
  // draw a frame 32×32 from (col = 1, row = 0)
  ctx.drawImage(hero,
      32, 0, 32, 32,   // sx, sy, sw, sh
      100, 100, 64, 64 // dx, dy, dw, dh
  );
};

// Streams: paint a <video> every frame
function tick(){
  ctx.drawImage(videoEl, 0, 0);
  requestAnimationFrame(tick);
}
		

Pixel-Level Manipulation

Reading and writing raw RGBA data.


const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imgData.data;   // Uint8ClampedArray [ r, g, b, a, … ]

for(let i = 0; i < data.length; i += 4){
  const gray = data[i]*0.21 + data[i+1]*0.72 + data[i+2]*0.07;
  data[i] = data[i+1] = data[i+2] = gray;   // desaturate
}
ctx.putImageData(imgData, 0, 0);
		

Pixel ops are CPU-heavy. Prefer OffscreenCanvas + Workers or WebGL shaders for real-time filters.

Transforms & Compositing

Scaling, rotation, clipping, and blend modes.


ctx.translate(cx, cy);
ctx.rotate(angle);
ctx.scale(scaleX, scaleY);

ctx.clip();                   // use current path as clip mask
ctx.globalCompositeOperation = "multiply";  // over, screen, overlay…
		
  1. Transforms multiply the current matrix; setTransform() resets directly.
  2. Use ctx.reset() (new) to clear path + transform + style.

Animation Loops & Timing

Running at the display’s refresh rate or fixed steps.


let last = performance.now();
function loop(time){
  const dt = (time - last) / 1000;  // seconds
  last = time;

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  update(dt);   draw();
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
		

For physics stability, update logic with a fixed step (e.g., 60 Hz) and interpolate during render.

OffscreenCanvas & Performance Tips

Parallel rendering, bitmap transfer, and resolution scaling.

  1. OffscreenCanvas lets you call canvas.transferControlToOffscreen() and render inside a Web Worker.
  2. Use requestIdleCallback for non-critical work.
  3. Batch state changes: group shapes that share fill/stroke style.
  4. Prefer downscaling rather than upscaling to support Hi-DPI (“devicePixelRatio”).

// main thread
const off = canvas.transferControlToOffscreen();
worker.postMessage({ canvas: off }, [off]);

// worker.js
onmessage = ({ data }) => {
  const ctx = data.canvas.getContext("2d");
  render(ctx);
};
		

WebGL Context Brief

Moving to GPU pipelines inside <canvas>.

Request with getContext("webgl2"). Draw calls are retained by the GPU until gl.flush(). Use shaders (.vert, .frag) and buffer objects.


const gl = canvas.getContext("webgl2");
const vs = `#version 300 es
in vec2 pos; void main(){ gl_Position = vec4(pos,0,1);} `;
const fs = `#version 300 es
precision mediump float; out vec4 col; void main(){ col = vec4(1,0,0,1);} `;
// compile, link, drawArrays(GL_TRIANGLES)…
		

Best Practices & Common Patterns

Maintainability, accessibility, and tooling.

  1. Isolate render logic from state update for clean MVC architecture.
  2. Provide fallback content inside <canvas>…</canvas> for screen readers.
  3. Use request-driven redraws; avoid setInterval for animation.
  4. Sprite batching: one off-screen buffer per layer to minimize overdraw.
  5. Profiling tools: Chrome DevTools → Performance panel → Frames mode.

Canvas Methods and Parameters Overview

A detailed guide covering essential Canvas methods and parameters.

Drawing Rectangles


fillRect(x, y, width, height)
Draws a filled rectangle. Parameters specify position and dimensions.

strokeRect(x, y, width, height)
Draws an outlined rectangle with the current stroke style.

clearRect(x, y, width, height)
Clears a rectangular area, making it fully transparent.
    

Path Methods


beginPath()
Starts a new drawing path.

moveTo(x, y)
Moves the drawing cursor to the specified coordinates.

lineTo(x, y)
Draws a straight line from the current position to the specified coordinates.

arc(x, y, radius, startAngle, endAngle, [anticlockwise])
Draws a circular arc centered at (x, y). Angles are in radians.

closePath()
Connects the last point of the path with the first point.

stroke()
Strokes the current path with the current stroke style.

fill()
Fills the current path with the current fill style.
    

Styling


fillStyle = color | gradient | pattern
Specifies the color or style to fill shapes.

strokeStyle = color | gradient | pattern
Defines the color or style to stroke paths.

lineWidth = number
Sets the thickness of lines.

createLinearGradient(x0, y0, x1, y1)
Creates a linear gradient object.

addColorStop(offset, color)
Adds a color stop to gradients. Offset ranges from 0.0 to 1.0.
    

Text Methods


fillText(text, x, y, [maxWidth])
Draws filled text at the given coordinates.

strokeText(text, x, y, [maxWidth])
Draws outlined text.

measureText(text)
Returns an object containing text metrics (width).
    

Image Methods


drawImage(image, dx, dy, [dw, dh])
Draws an image at (dx, dy), optionally scaled to dw, dh.

drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
Draws a subsection of the image (source rectangle) scaled to destination rectangle.
    

Pixel Manipulation


getImageData(x, y, width, height)
Extracts pixel data from the canvas area specified.

putImageData(imageData, x, y)
Draws pixel data onto the canvas at position x, y.
    

Transformations


translate(x, y)
Moves the canvas origin to the specified coordinates.

rotate(angle)
Rotates the canvas clockwise by the angle (in radians).

scale(x, y)
Scales the canvas units by x and y factors.

save()
Saves the current state (transformations, styles).

restore()
Restores to the previously saved state.

resetTransform()
Resets transformations to default.
    

Animation


requestAnimationFrame(callback)
Queues animation callback to run at display refresh rate.
    

Use this guide as a reference for building efficient and interactive graphics applications with Canvas in JavaScript.

Gallery (Examples Output)

Scrollable grid of rendered frames.

gradient demo sprite animation pixel filter WebGL triangle