Introduction to Graphics in HTML
HTML provides several ways to create and display graphics:
HTML5 Canvas
Pixel-based drawing surface for dynamic, scriptable rendering of 2D shapes and bitmap images.
SVG
Vector-based graphics in XML format that scales without quality loss.
Key differences:
Feature | Canvas | SVG |
---|---|---|
Type | Raster (pixel-based) | Vector (XML-based) |
DOM Access | No | Yes |
Performance | Better for complex scenes | Better for fewer objects |
Drawing with HTML5 Canvas
Basic canvas setup:
<canvas id="myCanvas" width="400" height="200"
style="border:1px solid #000000;">
Your browser does not support the canvas element.
</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Drawing examples
ctx.fillStyle = 'red';
ctx.fillRect(20, 20, 150, 100);
ctx.beginPath();
ctx.arc(300, 70, 50, 0, 2 * Math.PI);
ctx.stroke();
</script>
Common canvas methods:
fillRect(x,y,w,h)
- Draw filled rectanglestrokeRect(x,y,w,h)
- Draw outlined rectangleclearRect(x,y,w,h)
- Clear area
beginPath()
- Start new pathmoveTo(x,y)
- Move penlineTo(x,y)
- Draw line
Tip: Canvas drawings are not responsive by default. Use JavaScript to resize canvas elements while maintaining aspect ratio.
Using Scalable Vector Graphics (SVG)
Basic SVG example:
<svg width="400" height="200" viewBox="0 0 400 200">
<rect x="20" y="20" width="150" height="100"
fill="blue" stroke="black" stroke-width="2"/>
<circle cx="300" cy="70" r="50"
fill="green" stroke="black" stroke-width="2"/>
<text x="50" y="150" font-family="Arial" font-size="20"
fill="red">SVG Text</text>
</svg>
Key SVG elements:
<rect>
- Rectangle<circle>
- Circle<ellipse>
- Ellipse
<line>
- Line<polygon>
- Polygon<polyline>
- Polyline
<path>
- Complex shapes<text>
- Text<g>
- Group
Advantages of SVG:
- Scales to any size without quality loss
- Can be styled with CSS
- Accessible via DOM
- Good for interactive graphics