Tutorials Logic, IN info@tutorialslogic.com

HTML Graphics Canvas SVG

HTML Canvas

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.

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 Examples
<canvas id="myCanvas" width="400" height="200"
        style="border: 1px solid #ccc;">
    Your browser does not support canvas.
</canvas>

HTML Canvas - JavaScript Example

HTML Canvas - JavaScript Example
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

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

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

Feature Canvas SVG
Type Bitmap (pixel-based) Vector (math-based)
Scalability Blurs when scaled up Scales perfectly at any size
DOM access No - drawn via JS only Yes - each shape is a DOM element
CSS styling No Yes
Performance Better for many objects (games) Better for fewer, complex shapes
Best for Games, real-time charts, image editing Icons, 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

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.

HTML Graphics Canvas SVG HTML structure check

HTML Graphics Canvas SVG HTML structure check
<section>
  <h2>HTML Graphics Canvas SVG</h2>
  <p>Use semantic structure so the content is readable and accessible.</p>
</section>

HTML Graphics Canvas SVG accessibility check

HTML Graphics Canvas SVG accessibility check
<button type="button" aria-label="Review HTML Graphics Canvas SVG">Review</button>
Before you move on

HTML Graphics Canvas SVG Mastery Check

5 checks
  • The 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.

HTML Questions Learners Ask

Canvas is pixel-based and drawn with JavaScript, while SVG is vector-based and made of DOM elements. Canvas is better for fast dynamic drawing, and SVG is better for scalable, styleable graphics.

SVG is usually better for logos and icons because it scales perfectly without losing quality and can be styled easily with CSS.

Yes. Canvas is commonly animated using JavaScript and <code>requestAnimationFrame()</code>, which redraws the scene smoothly as values change.

Browse Free Tutorials

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