HTML Canvas Basics
The HTML <canvas> element gives you a
blank bitmap surface you can draw on with JavaScript — shapes, text, images, gradients, and animations — all
rendered in real time by the browser. Canvas powers browser games, data visualisations, image editors,
signature pads, and interactive infographics. In this chapter you'll master the 2D rendering context, the
coordinate system, every core drawing method, and how to animate with requestAnimationFrame.
<canvas> element and
getContext('2d')
requestAnimationFrameThe <canvas> Element
The <canvas> element creates a
rectangular bitmap drawing surface on the page. It has no drawing API of its own — all
drawing is done through JavaScript via a rendering context. The most common context is
'2d' (the Canvas 2D API). You can also use 'webgl' for 3D graphics, but that is beyond this chapter.
getElementById
style="width:600px") scales the canvas
after rendering, producing blurry output. Always set width and
height as HTML attributes — these define the actual pixel buffer. Use
CSS only for display sizing (e.g. responsive scaling). If you need a responsive canvas, set the HTML
attributes to a high resolution and scale down with max-width: 100% in
CSS.
The Canvas Coordinate System
The canvas uses a pixel-based 2D coordinate system. The origin (0, 0) is at the top-left corner. X increases to the right,
Y increases downward. This is different from standard maths graphs where Y increases upward — keep this in
mind when placing elements.
(0, 0) = top-left. X grows right. Y grows
downward (opposite of school maths). To centre something on a 600×300 canvas, its position
is (300, 150). Use canvas.width / 2
and canvas.height / 2 in code — never hard-code centre coordinates.
Drawing Rectangles
Rectangles are the only shape with dedicated methods — all other shapes require paths.
All rectangle methods take four arguments: (x, y, width, height).
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// fillRect(x, y, width, height) — filled rectangle
ctx.fillStyle = '#e44d26';
ctx.fillRect(20, 20, 140, 80);
// strokeRect(x, y, width, height) — outline only
ctx.strokeStyle = '#3b82f6';
ctx.lineWidth = 3;
ctx.strokeRect(180, 20, 140, 80);
// clearRect(x, y, width, height) — erases pixels
ctx.clearRect(50, 40, 60, 40); // cut a hole in the orange rect
// Rounded rectangle (modern — Chrome 99+, Firefox 112+)
ctx.beginPath();
ctx.roundRect(340, 20, 140, 80, 16); // radius = 16
ctx.fillStyle = '#22c55e';
ctx.fill();
Paths — Lines, Arcs & Custom Shapes
Most canvas drawing uses the path API. A path is a sequence of points
connected by lines or curves. The general flow is always: beginPath() →
draw path commands → fill() and/or stroke().
// ── Triangle (3 lineTo calls) ─────────────────────── //
ctx.beginPath();
ctx.moveTo(80, 20); // starting point (tip)
ctx.lineTo(20, 140); // bottom-left
ctx.lineTo(140, 140); // bottom-right
ctx.closePath(); // auto-connect back to start
ctx.fillStyle = '#a855f7';
ctx.strokeStyle = '#7c3aed';
ctx.lineWidth = 2;
ctx.fill();
ctx.stroke();
// ── Circle (arc with full 2π sweep) ──────────────── //
// arc(x, y, radius, startAngle, endAngle, anticlockwise?)
ctx.beginPath();
ctx.arc(240, 80, 60, 0, Math.PI * 2);
ctx.fillStyle = '#f59e0b';
ctx.strokeStyle = '#d97706';
ctx.lineWidth = 3;
ctx.fill();
ctx.stroke();
// ── Semicircle (half arc) ─────────────────────────── //
ctx.beginPath();
ctx.arc(400, 140, 60, Math.PI, 0); // half circle (top)
ctx.closePath();
ctx.fillStyle = '#06b6d4';
ctx.strokeStyle = '#0891b2';
ctx.fill();
ctx.stroke();
// ── Diagonal line ─────────────────────────────────── //
ctx.beginPath();
ctx.moveTo(340, 20);
ctx.lineTo(500, 160);
ctx.strokeStyle = '#e44d26';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // round | square | butt
ctx.stroke();
0 =
3 o'clock, Math.PI / 2 = 6 o'clock, Math.PI = 9 o'clock, Math.PI * 2 = full
circle (back to 3 o'clock). Convert: degrees × Math.PI / 180.
Drawing Text
Canvas provides two text-drawing methods and several style properties. Text is drawn as rasterised pixels — it is not DOM text, so it cannot be selected, copied, or accessed by screen readers without additional effort.
// ── Font and alignment ───────────────────────────── //
ctx.font = 'bold 28px "Segoe UI", sans-serif';
ctx.textAlign = 'center'; // left | center | right | start | end
ctx.textBaseline = 'middle'; // top | middle | bottom | alphabetic
// ── fillText(text, x, y) — solid filled text ─────── //
ctx.fillStyle = '#e44d26';
ctx.fillText('K2infocom', 300, 60);
// ── strokeText(text, x, y) — outline text ────────── //
ctx.strokeStyle = '#3b82f6';
ctx.lineWidth = 1.5;
ctx.strokeText('HTML Canvas', 300, 100);
// ── measureText — get text width before drawing ──── //
const metrics = ctx.measureText('K2infocom');
console.log(metrics.width); // pixel width of text string
// ── Constrained text (max width) ─────────────────── //
ctx.fillText('Vadodara Web Dev', 300, 140, 200); // max 200px
Styling — Colours, Shadows & Gradients
Canvas accepts any CSS colour string for fill and stroke. You can also paint with
gradients or patterns by assigning them to fillStyle or strokeStyle.
// ── Linear gradient ───────────────────────────────── //
// createLinearGradient(x0, y0, x1, y1)
const linGrad = ctx.createLinearGradient(0, 0, 200, 0);
linGrad.addColorStop(0, '#e44d26'); // start colour
linGrad.addColorStop(0.5, '#f59e0b'); // midpoint
linGrad.addColorStop(1, '#22c55e'); // end colour
ctx.fillStyle = linGrad;
ctx.fillRect(20, 20, 200, 100);
// ── Radial gradient ───────────────────────────────── //
// createRadialGradient(x0, y0, r0, x1, y1, r1)
const radGrad = ctx.createRadialGradient(350, 70, 0, 350, 70, 80);
radGrad.addColorStop(0, '#ffffff'); // inner: white
radGrad.addColorStop(0.5, '#a855f7'); // mid: purple
radGrad.addColorStop(1, '#1e1e2a'); // outer: dark
ctx.beginPath();
ctx.arc(350, 70, 80, 0, Math.PI * 2);
ctx.fillStyle = radGrad;
ctx.fill();
// ── Shadows ───────────────────────────────────────── //
ctx.shadowColor = 'rgba(228,77,38,0.6)';
ctx.shadowBlur = 20;
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.fillStyle = '#fff';
ctx.fillRect(460, 30, 60, 80);
// Reset shadow so it doesn't affect later draws
ctx.shadowColor = 'transparent';
Core 2D Context Methods — Reference Cards
Here is a quick-reference summary of every essential Canvas 2D method grouped by category:
beginPath() and
ends with fill() / stroke().
font, textAlign, textBaseline before
calling.fillStyle.Drawing Images on Canvas
drawImage() copies pixel data from an HTMLImageElement, another canvas, or a video frame onto the canvas surface.
The image must be fully loaded before you call drawImage() — use the onload event
handler.
const img = new Image();
img.src = 'course-banner.jpg';
img.onload = () => {
// ── Basic: draw at (x, y) in its natural size ── //
ctx.drawImage(img, 0, 0);
// ── Scaled: draw at (x, y) with specific width/height ── //
ctx.drawImage(img, 10, 10, 200, 120);
// ── Cropped: 9-argument form
// src crop: (sx, sy, sWidth, sHeight)
// dest: (dx, dy, dWidth, dHeight) ────────── //
ctx.drawImage(
img,
50, 0, 400, 300, // crop from source
0, 0, 200, 150 // draw into canvas at this size
);
};
Canvas Animation with requestAnimationFrame
Canvas animation works by clearing and redrawing every frame —
typically 60 times per second. requestAnimationFrame(callback) asks the
browser to call your function before the next repaint, syncing perfectly with the display refresh rate and
pausing automatically when the tab is hidden.
requestAnimationFrame
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width, H = canvas.height;
// Ball state
let x = 60, y = H / 2;
let vx = 3, vy = 2; // velocity (px per frame)
const r = 28; // radius
function draw() {
// 1. Clear the entire canvas each frame
ctx.clearRect(0, 0, W, H);
// 2. Draw ball
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fillStyle = '#e44d26';
ctx.fill();
// 3. Update position
x += vx;
y += vy;
// 4. Bounce off walls
if (x + r > W || x - r < 0) vx = -vx;
if (y + r > H || y - r < 0) vy = -vy;
// 5. Schedule next frame
requestAnimationFrame(draw);
}
draw(); // kick off the loop
ctx.save() before
changing fill/stroke/transform, and ctx.restore() afterward. This pops
the state stack back — preventing one object's styles from "leaking" into the next. Think of it as pushing
and popping a settings undo stack.
Common Mistakes — Do's & Don'ts
These are the most frequent canvas mistakes beginners make:
// Size via HTML attributes — crisp pixels
<canvas width="600" height="300"></canvas>
// Wait for image to load before drawing
img.onload = () => {
ctx.drawImage(img, 0, 0);
};
// beginPath() before every new shape
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fill();
// CSS size only — blurry canvas!
<canvas style="width:600px"></canvas>
// Drawing before image is loaded — blank!
img.src = 'photo.jpg';
ctx.drawImage(img, 0, 0); // too early
// Missing beginPath — prev path merges in
ctx.fillStyle = 'red';
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fill(); // fills whole previous path too
Try It Yourself
The editor below has a complete canvas demo with shapes, text, gradients, and a bouncing animation. Click Open in Editor to see it in full screen and experiment with the code.
vx = 3.5 to vx = 8 and watch the ball fly faster. Change the ball's gradient colours.
Try adding a second ball by duplicating the state variables. Click Pause — it calls cancelAnimationFrame(animId) to stop the loop. Click Start
to resume.
Quick Check — Chapter 19
Expand each question to check your understanding before moving on to the multiple choice quiz.
<canvas> element has two separate size concepts: its
internal pixel buffer (set by the width and height HTML attributes) and its display size (set by
CSS). If you only set CSS dimensions without HTML attributes, the canvas defaults to a 300×150 pixel
buffer. The browser then scales this tiny buffer up to fit the CSS size — stretching those 300×150
pixels across a much larger display area — producing blurry, pixelated output. Always set width and height HTML attributes to
match the actual pixel dimensions you want to draw at. Use CSS solely for controlling how the canvas
displays on screen (e.g. responsive scaling with max-width: 100%).
beginPath() resets this list,
discarding all previously added sub-paths. Without it, every new lineTo(), arc(), or other path
command is appended to the existing path. When you then call fill() or stroke(), the entire
accumulated path is drawn — so your new shape renders together with all the old paths, potentially
inheriting the wrong styles. Always call beginPath() before starting
a new independent shape.
(0, 0) is at the top-left corner
of the canvas element. The X axis increases to the right (normal). The Y axis increases
downward — the opposite of a standard maths coordinate system where Y increases upward.
This means (canvas.width/2, canvas.height/2) is the centre of the
canvas, and drawing at y = 0 places something at the top. This
downward Y direction is common to all 2D computer graphics systems. When implementing physics (gravity,
jumping), this means gravity adds to Y velocity — a positive vy
moves objects downward.
requestAnimationFrame has several advantages over setInterval: it syncs to the monitor's refresh rate
(typically 60Hz or 120Hz) — resulting in buttery smooth motion with no tearing. It automatically
pauses when the browser tab is not visible — saving CPU and battery. It calls your function
at the optimal time before the browser repaints — eliminating the visual stutter that setInterval can cause by firing at wrong moments in the paint cycle. The
callback receives a timestamp argument (milliseconds since page
load) that you can use for time-based animation — making speed independent of frame
rate. Use cancelAnimationFrame(id) with the returned ID to stop the
loop.
ctx.save() pushes the current drawing state onto a
stack — saving all style properties (fillStyle, strokeStyle, lineWidth, font, globalAlpha,
shadowColor, etc.) and all transformation matrices (translate, rotate, scale). ctx.restore() pops the most recent saved state,
restoring everything to what it was at the time of the last save()
call. This is essential when drawing complex scenes: save state, apply special transforms/styles for one
element, draw it, restore — the next element starts from a clean slate. They work as a push/pop
stack, so you can nest multiple save/restore pairs.
ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2); ctx.fill(); The
arc() method draws an arc from a start angle to an end angle in
radians. A full circle sweeps 2π radians (approximately 6.28 radians)
— this is Math.PI * 2. Starting at 0 (the 3 o'clock position) and sweeping to 2π completes a full 360° circle. To draw a semicircle, sweep from 0 to Math.PI (180°). Convert any
degree value to radians with: degrees × Math.PI / 180.
ctx.arc(x, y, r, 0, ?)?(0, 0) on the canvas
coordinate system?<canvas id="c" width="600" height="300">creates the drawing surface. Always use HTML attributes for dimensions — never CSS-only sizing. Get the 2D context withcanvas.getContext('2d').- The coordinate origin
(0,0)is the top-left corner. X increases right, Y increases downward. Convert degrees to radians withdeg × Math.PI / 180. - Rectangles:
fillRect,strokeRect,clearRect. Paths: alwaysbeginPath()→ draw commands →fill()/stroke(). Circles:arc(x, y, r, 0, Math.PI * 2). - Styling: set
fillStyle/strokeStyleto any CSS colour, or a gradient object. Gradients:createLinearGradient/createRadialGradient+addColorStop(offset, color). - Animation:
requestAnimationFrame(fn)syncs to the display refresh rate, pauses when tab hidden. Each frame:clearRect→ update state → redraw. Stop withcancelAnimationFrame(id). ctx.save()/ctx.restore()push/pop all style + transform state — essential for drawing multiple elements with different styles.drawImage(img, x, y)requires the image to be fully loaded viaimg.onload.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions, and stay updated with new tutorials.