Introduction to HTML Graphics
HTML graphics help make your website visually appealing and interactive. They allow you to create charts, games, animations, and more using graphics elements directly on a webpage.
There are two main ways to draw graphics in HTML:
There are two main ways to draw graphics in HTML:
1. HTML <canvas>
Used for drawing graphics via JavaScript (raster-based)
2. HTML <svg>
Used for drawing graphics via JavaScript (raster-based)
- Ideal for dynamic graphics, like games or animations
- Works with pixels (bitmap rendering)
- Great for performance-intensive visual content
2. HTML <svg>
Used for scalable vector graphics (XML-based)
- Best for static, scalable illustrations
- Maintains quality at any size (resolution-independent)
- Easy to style and animate via CSS or JavaScript
Why Use HTML Graphics?
Using graphics on web pages adds engagement and clarity for users. HTML graphics are commonly used in:
Example: Canvas in Action
Output:
.webp)
Example: SVG in Action
Output:
.webp)
Using graphics on web pages adds engagement and clarity for users. HTML graphics are commonly used in:
- Data visualization (e.g., charts and graphs)
- Game development
- Animated visuals and infographics
- Custom user interface (UI) elements
Canvas vs. SVG – When to Use ?
Feature | HTML Canvas | HTML SVG |
---|---|---|
Type | Raster ( pixel-based) | Vector ( scalable graphics ) |
Ideal For | Games, animations, complex visuals | Diagrams, icons, charts, UI elements |
Scalability | Loses quality when zoomed | Perfectly scalable at any resolution |
Interactivity | Managed manually with JS | Built-in event handling (click, hover) |
Performance | High for intensive rendering | Better for simpler/static visuals |
Example: Canvas in Action
<!DOCTYPE html><html><head> <title>Canvas Example</title></head><body> <canvas id="myCanvas" width="500" height="500"></canvas>
<script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'lightgreen'; ctx.fillRect(11, 10, 150, 100); </script></body></html>
Output:
.webp)
Example: SVG in Action
<!DOCTYPE html><html><head> <title>SVG Example</title></head><body> <h1>SVG Example</h1> <svg width="500" height="500" style="border:1px solid #000000;"> <!-- Draw a blue rectangle --> <rect x="50" y="50" width="200" height="100" fill="blue" /> </svg></body></html>
Output:
.webp)
Two Minute Drill
- Use <canvas> when you need real-time drawing, animations or pixel-level control.
- Use <svg> when you need scalable, easily styled graphics for UI and static visuals.