Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Compiler Tools

HTML Graphics — Canvas and SVG Guide

HTML5 provides two main ways to create graphics directly in the browser: Canvas and SVG. Both let developers build visual experiences without depending on image files for every shape, line, or effect.

Graphics in HTML are used in many real projects, such as charts, dashboards, games, logos, diagrams, interactive maps, drawing tools, and animations. Choosing the right approach depends on whether you need pixel-based rendering or scalable vector elements.

HTML Canvas

The <canvas> element is a bitmap-based drawing surface. It starts as an empty rectangular area, and JavaScript is used to draw shapes, lines, text, images, and animations onto it. Once something is drawn, the browser treats it as pixels rather than individual DOM elements.

Canvas is especially useful for games, real-time charts, particle effects, custom drawing tools, and image manipulation. It is fast and flexible, but because drawn items are not separate DOM nodes, they cannot be individually styled with CSS in the same way SVG elements can.

Canvas Examples
<canvas id="myCanvas" width="400" height="200"
        style="border: 1px solid #ccc;">
    Your browser does not support canvas.
</canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Draw a filled rectangle
ctx.fillStyle = '#e74c3c';
ctx.fillRect(20, 20, 150, 80);

// Draw a circle
ctx.beginPath();
ctx.arc(300, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = '#3498db';
ctx.fill();

// Draw text
ctx.font = '20px Arial';
ctx.fillStyle = '#2c3e50';
ctx.fillText('Hello Canvas!', 20, 160);

// Draw a line
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(400, 200);
ctx.strokeStyle = '#27ae60';
ctx.lineWidth = 2;
ctx.stroke();

Working with the Canvas Context

Before drawing on a canvas, we must get its rendering context using getContext('2d'). This context object provides methods such as fillRect(), strokeRect(), arc(), moveTo(), lineTo(), and fillText().

Think of the canvas context as a toolbox for drawing. Each method handles a different graphical task, and properties like fillStyle, strokeStyle, and lineWidth control the appearance of the output.

Canvas basics
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

ctx.fillStyle = '#8b5cf6';
ctx.fillRect(10, 10, 120, 60);

ctx.strokeStyle = '#111827';
ctx.lineWidth = 3;
ctx.strokeRect(150, 10, 120, 60);

SVG - Scalable Vector Graphics

SVG stands for Scalable Vector Graphics. It uses XML-based markup to describe shapes such as circles, rectangles, lines, paths, and text. Unlike Canvas, SVG graphics are part of the DOM, which means each shape behaves like an HTML element that can be styled with CSS and manipulated with JavaScript.

SVG is ideal when you need graphics that stay sharp at any resolution, such as icons, logos, illustrations, charts, flow diagrams, and responsive UI decorations. Since vector graphics are based on mathematical shapes rather than pixels, they scale cleanly without becoming blurry.

SVG Examples
<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">

    <!-- Rectangle -->
    <rect x="10" y="10" width="150" height="80"
          fill="#e74c3c" rx="8" ry="8"/>

    <!-- Circle -->
    <circle cx="300" cy="100" r="50"
            fill="#3498db" stroke="#2980b9" stroke-width="3"/>

    <!-- Line -->
    <line x1="0" y1="0" x2="400" y2="200"
          stroke="#27ae60" stroke-width="2"/>

    <!-- Text -->
    <text x="20" y="160" font-size="18" fill="#2c3e50">Hello SVG!</text>

    <!-- Polygon (triangle) -->
    <polygon points="200,10 250,90 150,90"
             fill="#f39c12"/>

</svg>

Styling and Animating SVG

Because SVG elements are part of the DOM, they can be targeted directly with CSS classes and JavaScript event handlers. This makes SVG a strong choice when you want hover effects, color changes, simple animations, or interaction on individual shapes.

SVG with CSS
<style>
.my-circle {
    fill: #2563eb;
    transition: fill 0.3s ease;
}

.my-circle:hover {
    fill: #dc2626;
}
</style>

<svg width="200" height="120">
    <circle class="my-circle" cx="80" cy="60" r="40"></circle>
</svg>

Canvas vs SVG

FeatureCanvasSVG
TypeBitmap (pixel-based)Vector (math-based)
ScalabilityBlurs when scaled upScales perfectly at any size
DOM accessNo - drawn via JS onlyYes - each shape is a DOM element
CSS stylingNoYes
PerformanceBetter for many objects (games)Better for fewer, complex shapes
Best forGames, real-time charts, image editingIcons, logos, diagrams, infographics

When to Use Canvas

  • Use Canvas for games, particle effects, and animations that redraw frequently.
  • Use Canvas for drawing applications, image filters, or custom data visualizations.
  • Use Canvas when performance matters more than DOM-level interaction with individual shapes.

When to Use SVG

  • Use SVG for icons, logos, diagrams, and graphics that must stay crisp at all sizes.
  • Use SVG when you want to style shapes with CSS or attach events to specific elements.
  • Use SVG for responsive UI graphics and lightweight interactive illustrations.

Simple Canvas Animation Idea

Canvas is often paired with requestAnimationFrame() for smooth animation. This browser API schedules drawing updates to match the screen refresh rate, which makes animations look better and perform more efficiently than using arbitrary time intervals.

Animation example
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = 20;

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#10b981';
    ctx.fillRect(x, 60, 50, 50);
    x += 2;

    if (x < canvas.width) {
        requestAnimationFrame(draw);
    }
}

draw();

Best Practices

  • Give canvas elements fallback text for browsers or assistive tools that cannot use them.
  • Set explicit width and height on canvas to avoid stretching the drawing surface unexpectedly.
  • Prefer SVG for resolution-independent graphics such as icons and UI illustrations.
  • Use CSS and semantic HTML around graphics so the page remains accessible and responsive.
  • Keep complex animation logic efficient to avoid unnecessary browser repaint costs.

Frequently Asked Questions

Key Takeaways
  • Canvas is a pixel-based drawing surface - use it for games, charts, and image manipulation.
  • SVG is vector-based - it scales perfectly at any size and is better for icons and logos.
  • Canvas requires JavaScript to draw; SVG can be styled with CSS and manipulated with JavaScript.
  • Use requestAnimationFrame for smooth canvas animations - it syncs with the display refresh rate.
  • SVG elements can be targeted with CSS selectors and JavaScript DOM methods.
  • For data visualization, consider libraries like Chart.js (canvas) or D3.js (SVG).

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.