Tutorials Logic, IN info@tutorialslogic.com

HTML Graphics Canvas SVG: Tutorial, Examples, FAQs & Interview Tips

HTML Graphics Canvas SVG

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.

Add one worked example that compares the normal path with the boundary case for HTML Graphics Canvas SVG.

HTML Graphics Canvas SVG should be studied as a practical HTML lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the html > graphics page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

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

HTML Canvas

HTML 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

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 in Real Work

HTML Graphics Canvas SVG matters in HTML because it changes how a program is written, tested, or debugged. The page should explain the normal flow first: what the developer writes, what the runtime or platform does, and what result should appear.

When teaching HTML Graphics Canvas SVG, avoid stopping at syntax. Show the surrounding decision: why this feature is chosen, what problem it removes, and what would become harder if the feature were not used.

  • Identify the concrete problem solved by HTML Graphics Canvas SVG.
  • Show the normal input, operation, and output for html.
  • Mention the nearby alternative a beginner may confuse with this topic.
  • Tie the explanation to a real project task, command, component, query, or debugging step.

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>
Key Takeaways
  • Explain the purpose of HTML Graphics Canvas SVG before memorizing syntax.
  • Run or trace one small HTML example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for HTML Graphics Canvas SVG.
  • Write the rule in your own words after checking the example.
  • Connect HTML Graphics Canvas SVG to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing HTML Graphics Canvas SVG without the situation where it is useful.
RIGHT Connect HTML Graphics Canvas SVG to a concrete HTML task.
Purpose makes syntax easier to recall.
WRONG Testing HTML Graphics Canvas SVG only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to HTML Graphics Canvas SVG.
Evidence keeps debugging focused.
WRONG Memorizing HTML Graphics Canvas SVG without the situation where it is useful.
RIGHT Connect HTML Graphics Canvas SVG to a concrete HTML task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to HTML Graphics Canvas SVG, then fix it and explain the fix.
  • Summarize when to use HTML Graphics Canvas SVG and when another approach is better.
  • Write a small example that uses HTML Graphics Canvas SVG in a realistic HTML scenario.
  • Change one important value in the HTML Graphics Canvas SVG example and predict the result first.

Frequently Asked Questions

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.

Yes. Since SVG elements are part of the DOM, you can target them with CSS selectors, apply colors, transitions, and even hover effects.

Ready to Level Up Your Skills?

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