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.
<canvas> and
getContext("2d")
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:
requestAnimationFrame — particles,
physics simulations, and interactive UI effects.
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.
<!-- 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>
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 |
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 |
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.
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
// 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.
// 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);
// 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";
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.
// 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
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.
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.
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
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.
// 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();
Best Practices
- Set
width/heightas HTML attributes, not only in CSS - Use
save()/restore()to scope transformations - Cancel animation loops with
cancelAnimationFrame(id)on cleanup - Reset
shadowColorto"transparent"after shadow draws - Scale for
devicePixelRatioon retina/HiDPI displays - Draw images inside the
img.onloadcallback
- 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
watchPositionor RAF loop running after navigation - Use canvas for text-heavy, accessible, or SEO-critical content
- Forget to clear the canvas before every animation frame
Which method must you call before drawing a new path to avoid re-drawing old paths?
- The Canvas API lives on the
<canvas>element — get its 2D context withcanvas.getContext("2d"). - Always set
widthandheightas HTML attributes, not only via CSS. - Rectangles have three direct methods:
fillRect(),strokeRect(), andclearRect(). - Paths require
beginPath()→ describe shape →fill()/stroke(). fillStyle/strokeStyleaccept CSS colours,CanvasGradient, orCanvasPattern.- Render text with
fillText()/strokeText()— canvas text is not accessible to screen readers. requestAnimationFrame(loop)drives smooth 60 fps animation — alwaysclearRectat the start of each frame.- Scope transformations with
save()/restore()to prevent state leaking between draw calls.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.