HTML5 SVG
SVG (Scalable Vector Graphics) is an XML-based markup language for describing two-dimensional vector graphics. It's an open standard from the W3C.
Unlike Canvas, SVG is not pixel-based but defines shapes through mathematical equations. This means you can infinitely enlarge SVG images without any quality loss, making them ideal for logos, icons, and illustrations requiring high fidelity.
Using SVG in HTML
You can embed <svg> tags directly into HTML documents to create graphics.
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>- The
<svg>element is the container for all SVG graphics. Thewidthandheightattributes define the SVG image dimensions. <circle>is one of the predefined SVG shapes, used to create a circle.cx,cydefine the center coordinates.rdefines the radius.strokeandstroke-widthdefine the outline color and width.filldefines the shape's fill color.
Advantages of SVG
- Scalability: Scales infinitely without distortion, looking crisp at any resolution.
- Accessibility: SVG is pure text XML, can be indexed by search engines, and accessed by screen readers. You can add titles and descriptions to SVG elements.
- Manipulability: Each SVG shape is a DOM element that can be styled with CSS and have interactions added with JavaScript (like event listeners), just like regular HTML elements.
- Small file size: For simple graphics, SVG files are usually smaller than bitmaps (like PNG, JPG).
Common SVG Shapes
SVG provides a series of predefined shape tags, making it very simple to create common graphics.
<rect>: Rectanglehtml<rect width="200" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" /><line>: Linehtml<line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" /><ellipse>: Ellipse<polygon>: Polygon (made up of multiple connected straight lines)<path>: Path. This is the most powerful SVG element, capable of creating any complex shape, including curves.
SVG vs. Canvas
Choosing SVG or Canvas depends on your specific needs:
| Feature | SVG | Canvas |
|---|---|---|
| Type | Vector graphics (shape-based) | Bitmap graphics (pixel-based) |
| DOM | Each shape is a DOM node | Single HTML element, no internal DOM |
| Scaling | Lossless scaling | Gets distorted when enlarged |
| Interaction | Can be manipulated directly via CSS and JS | Requires JS events and coordinate calculations |
| Use Cases | Icons, logos, charts, maps | Games, image processing, complex scene rendering |
Rule of thumb: If you need static, interactive, high-fidelity graphics, prefer SVG. If you need to process many pixels, do real-time rendering, or develop games, Canvas is a better choice.