Chapter 1 of ?
html 8 min read

HTML Mastery — Chapter 12: HTML Canvas 2D Graphics

Section 4 · Chapter 12

HTML Canvas 2D Graphics

The HTML <canvas> element provides an immediate-mode bitmap surface for drawing real-time 2D graphics, vector shapes, charts, image filters, and game animations using JavaScript's CanvasRenderingContext2D API.

Live Code Example

Click Try it Yourself » to execute JavaScript canvas drawing commands live in the interactive playground environment.

Example: Drawing Shapes, Gradients & Text on Canvas

<canvas id="demoCanvas" width="400" height="180" style="border:1px solid #cbd5e1; border-radius:8px;"></canvas> <script> const canvas = document.getElementById("demoCanvas"); const ctx = canvas.getContext("2d"); // 1. Draw Linear Gradient Rectangle const grad = ctx.createLinearGradient(0, 0, 180, 0); grad.addColorStop(0, "#4f46e5"); grad.addColorStop(1, "#06b6d4"); ctx.fillStyle = grad; ctx.fillRect(20, 20, 150, 90); // 2. Draw Arc Circle ctx.beginPath(); ctx.arc(280, 65, 45, 0, 2 * Math.PI); ctx.fillStyle = "#10b981"; ctx.fill(); ctx.lineWidth = 3; ctx.strokeStyle = "#047857"; ctx.stroke(); // 3. Render Canvas Text ctx.font = "bold 16px sans-serif"; ctx.fillStyle = "#0f172a"; ctx.fillText("HTML5 2D Canvas Engine", 20, 150); </script>
Try it Yourself »

12.1 The <canvas> Element & 2D Context (getContext('2d'))

The <canvas> element is a container for graphics. You must use JavaScript to draw on the bitmap buffer surface. The JavaScript method canvas.getContext('2d') obtains the built-in 2D rendering context object containing all drawing properties and algorithms.

Canvas Attributes vs CSS Sizing: Canvas internal resolution is defined strictly using HTML attributes (e.g., width="400" height="200"). Setting canvas width/height solely in CSS will stretch the pixel buffer and blur the graphic output.

Canvas 2D Coordinate Grid System & Raster Pixel Buffer

(0,0) Top-Left Origin fillRect(x=100, y=50, w=200, h=100) Raster Buffer (RGBA) • width: 400px • height: 200px • format: 32-bit RGBA • memory: 320 KB const ctx = canvas.getContext("2d");

Try It Yourself: Initializing Canvas & 2D Context

<canvas id="ctxCanvas" width="350" height="120" style="border:1px solid #cbd5e1; background:#f8fafc;"></canvas> <script> const c = document.getElementById("ctxCanvas"); const ctx = c.getContext("2d"); // Draw border line inside context ctx.strokeStyle = "#6366f1"; ctx.lineWidth = 4; ctx.strokeRect(10, 10, 330, 100); </script>
Try it Yourself »

12.2 Rectangles & Path Commands

The 2D context provides three helper methods to draw rectangles directly, as well as low-level path commands (beginPath(), moveTo(), lineTo(), closePath()) to create sub-paths and vector polygons.

Method Description Example
fillRect(x, y, w, h) Draws a filled rectangle using current fillStyle. ctx.fillRect(20, 20, 100, 50);
strokeRect(x, y, w, h) Draws an outlined rectangle using strokeStyle & lineWidth. ctx.strokeRect(140, 20, 100, 50);
clearRect(x, y, w, h) Clears pixels in specified rectangle, setting them to transparent black. ctx.clearRect(40, 30, 40, 30);
beginPath() / stroke() Resets current sub-path list and draws path stroke line. ctx.beginPath(); ctx.stroke();

Try It Yourself: Rectangles & Custom Polygons

<canvas id="rectCanvas" width="360" height="150" style="border:1px solid #cbd5e1; background:#f8fafc;"></canvas> <script> const c = document.getElementById("rectCanvas"); const ctx = c.getContext("2d"); // Filled Rect ctx.fillStyle = "#4f46e5"; ctx.fillRect(20, 20, 100, 70); // Clear Inner Rect Hole ctx.clearRect(45, 35, 50, 40); // Custom Triangle Path ctx.beginPath(); ctx.moveTo(180, 90); ctx.lineTo(240, 20); ctx.lineTo(300, 90); ctx.closePath(); ctx.fillStyle = "#10b981"; ctx.fill(); ctx.lineWidth = 3; ctx.strokeStyle = "#047857"; ctx.stroke(); </script>
Try it Yourself »

12.3 Arcs, Circles & Curves

Circles and circular arcs are created using the arc(x, y, radius, startAngle, endAngle, counterclockwise) method. Angles in Canvas 2D are measured in radians (radians = (degrees * Math.PI) / 180).

Try It Yourself: Circles, Arcs & Smiley Face

<canvas id="arcCanvas" width="340" height="160" style="border:1px solid #cbd5e1; background:#f8fafc;"></canvas> <script> const c = document.getElementById("arcCanvas"); const ctx = c.getContext("2d"); // Outer Face Circle ctx.beginPath(); ctx.arc(170, 80, 60, 0, Math.PI * 2); ctx.fillStyle = "#fef08a"; ctx.fill(); ctx.lineWidth = 3; ctx.strokeStyle = "#ca8a04"; ctx.stroke(); // Left Eye ctx.beginPath(); ctx.arc(145, 65, 8, 0, Math.PI * 2); ctx.fillStyle = "#0f172a"; ctx.fill(); // Right Eye ctx.beginPath(); ctx.arc(195, 65, 8, 0, Math.PI * 2); ctx.fillStyle = "#0f172a"; ctx.fill(); // Smile Arc ctx.beginPath(); ctx.arc(170, 80, 38, 0.2 * Math.PI, 0.8 * Math.PI); ctx.lineWidth = 4; ctx.strokeStyle = "#0f172a"; ctx.stroke(); </script>
Try it Yourself »

12.4 Colors, Gradients & Text Rendering

Canvas context supports solid colors, linear gradients (createLinearGradient(x0, y0, x1, y1)), radial gradients (createRadialGradient(...)), and typography rendering using fillText() and strokeText().

Canvas Rendering Engine Execution Pipeline

1. Context State Set fillStyle, font & strokeStyle 2. Path / Geometry beginPath(), rect(), arc(), or moveTo() 3. Draw Operation fill(), stroke(), or fillText() 4. Raster Pixels Hardware GPU Blit Output

Try It Yourself: Gradients & Stroked Typography

<canvas id="textCanvas" width="380" height="140" style="border:1px solid #cbd5e1; background:#0f172a;"></canvas> <script> const c = document.getElementById("textCanvas"); const ctx = c.getContext("2d"); // Create Linear Gradient const gradient = ctx.createLinearGradient(0, 0, 380, 0); gradient.addColorStop(0, "#f43f5e"); gradient.addColorStop(0.5, "#8b5cf6"); gradient.addColorStop(1, "#06b6d4"); // Render Filled Text ctx.font = "800 28px Outfit, sans-serif"; ctx.fillStyle = gradient; ctx.fillText("HTML5 CANVAS 2D", 20, 60); // Render Stroked Text Outline ctx.font = "700 22px Fira Code, monospace"; ctx.strokeStyle = "#38bdf8"; ctx.lineWidth = 1.5; ctx.strokeText("INTERACTIVE ENGINE", 20, 105); </script>
Try it Yourself »

12.5 Interactive Canvas Studio & Image Rendering

Use the interactive studio widget below to draw shapes, lines, circles, and custom text live onto the canvas viewport.

Live Interactive 2D Canvas Drawing Studio

Try It Yourself: Interactive Canvas Drawing Studio Script

<canvas id="studioDemo" width="400" height="150" style="border:1px solid #cbd5e1; background:#0f172a;"></canvas> <script> const canvas = document.getElementById("studioDemo"); const ctx = canvas.getContext("2d"); // Draw Star Shape ctx.fillStyle = "#8b5cf6"; ctx.strokeStyle = "#38bdf8"; ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(200, 20); ctx.lineTo(215, 60); ctx.lineTo(255, 60); ctx.lineTo(223, 85); ctx.lineTo(235, 125); ctx.lineTo(200, 100); ctx.lineTo(165, 125); ctx.lineTo(177, 85); ctx.lineTo(145, 60); ctx.lineTo(185, 60); ctx.closePath(); ctx.fill(); ctx.stroke(); </script>
Try it Yourself »

💻 Chapter 12 Hands-On Code Challenge

Build a Canvas Banner featuring a linear gradient background, a filled arc circle badge, and a custom stroked text header:

Key Takeaways & Summary

  • Immediate Mode Bitmap: The <canvas> element draws pixels directly into a 32-bit raster buffer. It does not create individual DOM elements for shapes.
  • Coordinate Origin: The (0,0) origin is located at the top-left corner of the canvas viewport.
  • 2D Context API: Obtain the drawing context using canvas.getContext('2d') to access methods like fillRect(), strokeRect(), arc(), createLinearGradient(), and fillText().
  • Path Lifecycle: Path drawing must start with beginPath() and finalize with stroke() or fill().
Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *