Skip to content
HTML Graphics Explained — Canvas & SVG for Beginners

HTML Graphics Explained — Canvas & SVG for Beginners

DodaTech Updated Jun 6, 2026 11 min read

HTML gives you two powerful ways to create graphics on a web page: Canvas (pixel-based drawing with JavaScript) and SVG (vector-based shapes in XML). This tutorial teaches both, with practical examples and clear guidance on when to use each.

What You’ll Learn

By the end of this tutorial, you’ll understand the difference between Canvas and SVG, draw shapes and text with both, add colors and gradients, and know which tool fits your project.

Prerequisite: You should understand basic HTML and JavaScript. HTML Basics and HTML JavaScript cover what you need.

Where This Fits in Your Learning Path

    flowchart LR
    A["Responsive HTML"] --> B["**Graphics (Canvas & SVG)**"]
    B --> C["Video, Audio & Media"]
    C --> D["HTML APIs"]
    D --> E["Frontend-Ready Developer"]
    style B fill:#f97316,stroke:#c2410c,color:#fff
    style A fill:#e5e7eb,stroke:#9ca3af,color:#374151
    style E fill:#22c55e,stroke:#16a34a,color:#fff
  

Canvas vs SVG — Which One Should You Use?

Before we dive into code, let’s understand the fundamental difference:

FeatureCanvasSVG
TypePixel-based (like a photograph)Vector-based (like shapes in Illustrator)
How it worksJavaScript draws pixels onto a gridXML defines shapes that the browser renders
ScalingGets blurry when zoomed in (pixels stretch)Stays sharp at any size (mathematical curves)
PerformanceFast with thousands of objectsSlows down with many objects
Event handlingYou must calculate where clicks happenEach shape can have its own click handler
Best forGames, image filters, animationsIcons, charts, logos, illustrations

Think of Canvas like a whiteboard where you draw with markers. Once you draw something, it’s just colored pixels — you can’t go back and move a shape. Think of SVG like a document that lists every shape: “circle at position X with radius Y.” The computer knows about each shape individually, so it can move, resize, or change colors later.

The golden rule: Use SVG for static or interactive graphics (icons, charts, diagrams). Use Canvas for dynamic, animated, or pixel-heavy graphics (games, image processing, real-time data viz).


SVG — Scalable Vector Graphics

SVG stands for Scalable Vector Graphics. “Scalable” means it looks sharp at any size — from a tiny phone screen to a giant billboard. “Vector” means it’s made of mathematical shapes, not pixels.

Your First SVG

<svg width="200" height="200" viewBox="0 0 200 200">
  <circle cx="100" cy="100" r="80" fill="#667eea" />
  <rect x="60" y="60" width="80" height="80" fill="white" opacity="0.5" />
</svg>

How it works:

  • <svg> creates a drawing area. width and height set the display size. viewBox defines the coordinate system (0 to 200 in both directions).
  • <circle cx="100" cy="100" r="80"> draws a circle centered at position (100, 100) with radius 80.
  • <rect x="60" y="60" width="80" height="80"> draws a square starting at position (60, 60), 80px wide and tall.
  • fill sets the fill color. opacity makes it semi-transparent.

Common SVG Shapes

<svg width="400" height="200" viewBox="0 0 400 200">
  <!-- Circle -->
  <circle cx="50" cy="100" r="40" fill="#e74c3c" />

  <!-- Rounded rectangle -->
  <rect x="120" y="60" width="80" height="80" rx="12" fill="#2ecc71" />

  <!-- Ellipse -->
  <ellipse cx="270" cy="100" rx="50" ry="30" fill="#f39c12" />

  <!-- Line -->
  <line x1="350" y1="30" x2="380" y2="170" stroke="#9b59b6" stroke-width="4" />

  <!-- Polygon -->
  <polygon points="200,30 220,80 270,80 230,110 245,160 200,130 155,160 170,110 130,80 180,80"
           fill="#1abc9c" />
</svg>

What’s happening: Each element is a separate shape. You can click on the circle without affecting the rectangle — the browser treats them as distinct objects in the document.

SVG Styling with Gradients

<svg width="300" height="150">
  <defs>
    <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" stop-color="#667eea" />
      <stop offset="100%" stop-color="#764ba2" />
    </linearGradient>
  </defs>

  <rect x="10" y="10" width="280" height="130" rx="12" fill="url(#grad)" />

  <text x="150" y="80" text-anchor="middle" fill="white"
        font-family="sans-serif" font-size="20">Gradient Background</text>
</svg>

Key parts:

  • <defs> stores definitions (gradients, filters) that you reuse with url(#id).
  • <linearGradient> defines a color transition. x1/y1 and x2/y2 set the direction (top-left to bottom-right here).
  • <stop> defines each color stop with an offset percentage.
  • The <rect> uses fill="url(#grad)" to reference the gradient.

SVG Text and Paths

SVG text works differently from HTML text — it follows the SVG coordinate system and can be transformed, rotated, or even placed along a path:

<svg width="400" height="200">
  <path d="M 10 100 Q 100 20 200 100 T 390 100"
        fill="none" stroke="#e74c3c" stroke-width="3" />
  <text fill="#333" font-size="16" font-family="sans-serif">
    <textPath href="#curvePath">Text along a curved path!</textPath>
  </text>
</svg>

This is just a taste — paths (d attribute) use a mini-language: M move, L line, Q quadratic curve, C cubic curve, Z close shape.


Canvas — Pixel-Based Drawing

Canvas is a JavaScript API. You get a blank grid of pixels and draw on it with code. Nothing is “remembered” — once drawn, it’s just pixels.

Your First Canvas Drawing

<canvas id="myCanvas" width="400" height="200"></canvas>

<script>
  // Step 1: Get the canvas element
  const canvas = document.getElementById('myCanvas');

  // Step 2: Get the 2D drawing context
  const ctx = canvas.getContext('2d');

  // Step 3: Draw a filled rectangle
  ctx.fillStyle = '#667eea';
  ctx.fillRect(20, 20, 150, 100);

  // Step 4: Draw a circle
  ctx.beginPath();
  ctx.arc(300, 80, 50, 0, Math.PI * 2);
  ctx.fillStyle = '#e74c3c';
  ctx.fill();

  // Step 5: Draw text
  ctx.font = '20px sans-serif';
  ctx.fillStyle = '#333';
  ctx.fillText('Hello Canvas!', 100, 160);
</script>

Step by step:

  1. <canvas id="myCanvas"> creates the canvas element. Always give it an id so JavaScript can find it.
  2. canvas.getContext('2d') gets the 2D drawing context — this is your “brush” and “paint” combined into one object.
  3. ctx.fillStyle sets the current fill color (like dipping your brush in paint).
  4. ctx.fillRect(x, y, width, height) draws a filled rectangle at the given position.
  5. For a circle: beginPath() starts a new shape, arc() defines it (center x, center y, radius, start angle, end angle), and fill() paints it.
  6. ctx.font sets the text style before drawing text with fillText().

Common Canvas Drawing Methods

MethodWhat it does
fillRect(x, y, w, h)Draws a filled rectangle
strokeRect(x, y, w, h)Draws an outlined rectangle (no fill)
clearRect(x, y, w, h)Erases pixels (makes them transparent)
beginPath()Starts a new shape
moveTo(x, y)Moves the pen to a position (no drawing)
lineTo(x, y)Draws a line from the current position to (x, y)
arc(x, y, r, start, end)Draws an arc or circle (angles in radians)
fill()Fills the current path with fillStyle
stroke()Outlines the current path with strokeStyle
fillText(text, x, y)Draws filled text at position

Drawing a Smiley Face with Canvas

<canvas id="smiley" width="200" height="200"></canvas>

<script>
  const c = document.getElementById('smiley');
  const ctx = c.getContext('2d');

  // Face (yellow circle)
  ctx.beginPath();
  ctx.arc(100, 100, 80, 0, Math.PI * 2);
  ctx.fillStyle = '#f1c40f';
  ctx.fill();
  ctx.strokeStyle = '#333';
  ctx.lineWidth = 3;
  ctx.stroke();

  // Left eye
  ctx.beginPath();
  ctx.arc(70, 80, 10, 0, Math.PI * 2);
  ctx.fillStyle = '#333';
  ctx.fill();

  // Right eye
  ctx.beginPath();
  ctx.arc(130, 80, 10, 0, Math.PI * 2);
  ctx.fill();

  // Smile (arc from 0.25 to 0.75 of a full circle, inverted)
  ctx.beginPath();
  ctx.arc(100, 100, 50, 0.2 * Math.PI, 0.8 * Math.PI);
  ctx.stroke();
</script>

Why this works: Canvas draws in order — later drawings appear on top of earlier ones. We draw the face first, then eyes, then smile. If we drew in the wrong order, things would be hidden.

Canvas with Animation

Canvas really shines when you need animation:

<canvas id="bounce" width="400" height="300"></canvas>

<script>
  const c = document.getElementById('bounce');
  const ctx = c.getContext('2d');
  let x = 50, y = 50;
  let dx = 3, dy = 2;

  function draw() {
    // Clear the canvas
    ctx.clearRect(0, 0, 400, 300);

    // Draw the ball
    ctx.beginPath();
    ctx.arc(x, y, 20, 0, Math.PI * 2);
    ctx.fillStyle = '#e74c3c';
    ctx.fill();

    // Move the ball
    x += dx;
    y += dy;

    // Bounce off walls
    if (x + 20 > 400 || x - 20 < 0) dx = -dx;
    if (y + 20 > 300 || y - 20 < 0) dy = -dy;

    requestAnimationFrame(draw);
  }

  draw();
</script>

Key insight: requestAnimationFrame(draw) tells the browser to call draw() on the next frame (about 60 times per second). Each frame clears the canvas and redraws everything in a new position. This is how games and interactive animations work.


When to Choose Which

    flowchart TD
    A["Need graphics in HTML?"]
    A --> B{"Interactive or animated?"}
    B -->|Yes, real-time| C["Canvas"]
    B -->|No, mostly static| D{"Need individual element control?"}
    D -->|Yes, clickable shapes| E["SVG"]
    D -->|No, just show it| F["Either works"]
    C --> G["Games, particle effects,\nimage processing"]
    E --> H["Icons, charts, diagrams,\ndata visualization"]
  

Security note: Canvas can read pixel data with getImageData(). This is used for image processing, but also for canvas fingerprinting (tracking users). Always inform users if your site uses canvas pixel reading, especially in regions covered by GDPR.


Common Graphics Mistakes

1. Drawing in the Wrong Order

// ❌ Wrong: eye drawn before face, so it's hidden
ctx.beginPath();
ctx.arc(70, 80, 10, 0, Math.PI * 2);  // Eye
ctx.fill();
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2);  // Face (covers the eye)
ctx.fillStyle = '#f1c40f';
ctx.fill();

// ✅ Correct: face first, then eye on top
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2);  // Face
ctx.fillStyle = '#f1c40f';
ctx.fill();
ctx.beginPath();
ctx.arc(70, 80, 10, 0, Math.PI * 2);  // Eye (on top)
ctx.fillStyle = '#333';
ctx.fill();

2. Forgetting beginPath()

// ❌ Wrong: second shape inherits style from first
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 50);
ctx.arc(100, 100, 30, 0, Math.PI * 2);  // Circles onto the previous path!

// ✅ Correct: start a fresh path
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 50);
ctx.beginPath();  // Reset path
ctx.arc(100, 100, 30, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();

3. Not Checking Canvas Support

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
  // ❌ Browser might not support canvas!
  canvas.innerHTML = 'Your browser does not support Canvas.';
}

4. Using SVG for Thousands of Objects

SVG creates a DOM element for every shape. 5,000 circles means 5,000 DOM nodes, which is slow. Canvas handles thousands of objects easily — it’s just pixels.

5. Not Setting Canvas Width/Height Correctly

<!-- ❌ Wrong: CSS changes stretch the canvas (blurry) -->
<canvas id="bad" style="width: 800px; height: 400px;"></canvas>

<!-- ✅ Correct: width/height attributes set the pixel grid -->
<canvas id="good" width="800" height="400"></canvas>

Try It Yourself

Draw a house using Canvas:

▶ Try It Yourself Edit the code and click Run

Common Mistakes Beginners Make

1. Skipping the Fundamentals

Many beginners jump straight to advanced topics without mastering the basics. Take time to understand the core concepts before moving on.

2. Not Practicing Enough

Reading tutorials without writing code leads to shallow understanding. Code along with every example and experiment on your own.

3. Ignoring Error Messages

Error messages tell you exactly what went wrong. Read them carefully — they usually point to the line and type of issue.

4. Copy-Pasting Without Understanding

It’s tempting to copy code from tutorials, but typing it yourself and understanding each line builds real skill.

5. Giving Up Too Early

Every developer hits frustrating bugs. Take breaks, ask for help, and remember that struggling is part of learning.

Practice Questions

Q1: What’s the main difference between Canvas and SVG?

Canvas is pixel-based (raster) — it draws pixels onto a grid. SVG is vector-based — it defines mathematical shapes. Canvas gets blurry when scaled, SVG stays sharp.

Q2: How do you get the drawing context for a canvas?

canvas.getContext('2d') — this returns the 2D rendering context you use to draw shapes, text, and images.

Q3: What does beginPath() do and why is it important?

It starts a new path (shape). Without it, new shapes get merged with previous ones, causing unexpected drawing behavior.

Q4: In SVG, what does <defs> contain?

Definitions like gradients, filters, and patterns that you reuse with url(#id).

Q5: How do you animate something on Canvas?

Use requestAnimationFrame() to repeatedly clear and redraw the canvas at ~60fps. Move objects slightly each frame to create animation.

Challenge

Create a Canvas-based “Starfield” animation:

  • Fill the canvas with black
  • Generate 100 random stars (white dots) at random positions
  • Make the stars slowly move downward (scroll effect)
  • When a star goes off the bottom, wrap it to the top

Real-World Task

Create an SVG logo for a fictional company called “HexCorp” — a hexagon with gradient fill, text inside, and at least one interactive element (like a hover effect using CSS).


Frequently Asked Questions

Can I use both Canvas and SVG on the same page?
Yes, absolutely. Many pages use SVG for icons and logos and Canvas for interactive elements. They’re independent technologies that coexist fine.
Which is better for charts and graphs?
SVG is generally better. Each bar or line in a chart is a DOM element that can be styled, animated, and made interactive. Libraries like D3.js use SVG. For real-time data with thousands of points, Canvas performs better.
Does Canvas work with CSS animations?
Canvas pixels aren’t DOM elements, so CSS can’t animate individual shapes. You must use JavaScript + requestAnimationFrame for Canvas animations.

What’s Next?

Now explore media and APIs:

What’s Next

Congratulations on completing this Html Graphics tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro