Tutorials HTML Canvas Basics
Ch 19 / 40
Chapter 19 Intermediate 10 min read HTML

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.

What you'll learn
The <canvas> element and getContext('2d')
The canvas coordinate system (origin, x, y, width, height)
Drawing rectangles, paths, lines, arcs, and circles
Styling — fill, stroke, colours, line width, shadows
Text, images, and linear / radial gradients
Canvas animation with requestAnimationFrame

The <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.

<canvas id="myCanvas" width="600" height="300" > Fallback text for browsers without canvas support. </canvas> // JavaScript — get the 2D context const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');
width / height Sets the pixel dimensions of the drawing surface — always use HTML attributes (not CSS) to avoid blurry scaled canvas
id Required to access the element via JavaScript with getElementById
Fallback text Content between canvas tags shown only in very old browsers that don't support canvas
getContext('2d') Returns the CanvasRenderingContext2D object — the drawing API that provides all methods
ctx Convention name for the 2D context — all drawing calls go through this object
Always Use HTML Attributes for Dimensions
Setting canvas size via CSS (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) X → Y ↓ width/2 height/2 canvas.width (e.g. 600px) canvas.height (190, 100)
Key Coordinate Facts
Origin (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).

Live Canvas — Rectangles rendered in the page
JavaScript — Rectangle methods
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().

Live Canvas — Paths: triangle, circle, star, and custom shape
JavaScript — Paths: triangle, circle, and custom line
// ── 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();
Arc Angles are in Radians
Canvas angles use radians, not degrees. Key values: 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.

JavaScript — Canvas text methods and properties
// ── 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.

Live Canvas — Linear gradient, radial gradient, and shadow
JavaScript — Linear gradient, radial gradient, shadows
// ── 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:

Rectangles 3 dedicated methods
The only shapes with direct methods — no path needed.
fillRect(x,y,w,h)
strokeRect(x,y,w,h)
clearRect(x,y,w,h)
Path Control Start, end, connect
Every custom shape starts with beginPath() and ends with fill() / stroke().
beginPath()
closePath()
moveTo(x, y)
lineTo(x, y)
Curves Arcs & beziers
Draw circles, arcs, and smooth curves using arc or bezier commands.
arc(x,y,r,start,end)
arcTo(x1,y1,x2,y2,r)
bezierCurveTo(cp1x,cp1y, cp2x,cp2y, x,y)
quadraticCurveTo(cpx,cpy,x,y)
Text Fill & outline text
Rasterised text drawn at a point. Set font, textAlign, textBaseline before calling.
fillText(text, x, y)
strokeText(text, x, y)
measureText(text) → width
Style Props Fill, stroke, line
Properties (not methods) — set before each drawing call.
fillStyle = color/gradient
strokeStyle = color/gradient
lineWidth = number
lineCap = round|square|butt
globalAlpha = 0–1
Gradients Linear & radial
Create gradient objects, add colour stops, then assign to fillStyle.
createLinearGradient(x0,y0,x1,y1)
createRadialGradient(x0,y0,r0, x1,y1,r1)
addColorStop(offset, color)
Images Draw pixels from img
Draw an HTMLImageElement onto the canvas. Must be fully loaded before drawing or you get a blank result.
drawImage(img, x, y)
drawImage(img, x, y, w, h)
drawImage(img, sx,sy,sw,sh, dx,dy,dw,dh)
State & Transform Save, restore, transform
Save and restore the drawing state (styles, transforms) and apply coordinate transformations.
save() / restore()
translate(x, y)
rotate(angle)
scale(x, y)

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.

JavaScript — drawImage examples
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.

Live Animation — Bouncing ball with requestAnimationFrame
JavaScript — requestAnimationFrame animation loop
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
Save / Restore for Complex Scenes
When drawing many objects with different styles, use 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:

Do — Correct
// 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();
Don't — Wrong
// 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.

Live Editor
✎ Editor
👁 Preview
Try This
In the editor: change 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.
Free Resource
HTML5 Cheat Sheet — All Tags & Attributes
One printable PDF covering all Canvas 2D context methods, the coordinate system, gradient API, animation loop pattern, and save/restore usage.
Download PDF
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React, and Node.js in one industry-ready curriculum with real projects and placement support.
120+
Chapters
40 hrs
Content
10
Projects
4.9 ⭐
Rating
HTML5 CSS3 JavaScript React.js Node.js MongoDB AI Tools

Quick Check — Chapter 19

Expand each question to check your understanding before moving on to the multiple choice quiz.

Questions & Answers
A <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%).
The canvas maintains an internal current path — a list of sub-paths that accumulates until you explicitly clear it. 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.
The canvas origin (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.
A full circle is drawn with: 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.
Multiple Choice Questions
MCQ 1 of 4
Which JavaScript method returns the 2D drawing context from a canvas element?
MCQ 2 of 4
What value of end angle draws a complete circle in ctx.arc(x, y, r, 0, ?)?
MCQ 3 of 4
Which method should you call to clear the entire canvas at the start of each animation frame?
MCQ 4 of 4
Where is the origin (0, 0) on the canvas coordinate system?
Chapter Summary
  • <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 with canvas.getContext('2d').
  • The coordinate origin (0,0) is the top-left corner. X increases right, Y increases downward. Convert degrees to radians with deg × Math.PI / 180.
  • Rectangles: fillRect, strokeRect, clearRect. Paths: always beginPath() → draw commands → fill()/stroke(). Circles: arc(x, y, r, 0, Math.PI * 2).
  • Styling: set fillStyle/strokeStyle to 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 with cancelAnimationFrame(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 via img.onload.
~10 min read
Intermediate level
Chapter 19 of 40

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
If this tutorial helped you, a 5-star Google review means a lot. It helps other learners discover our free content and motivates us to keep improving.
500+ Reviews (Target)
Write a Google Review
Join WhatsApp Channel