<svg>
The <svg>
tag is used to create and manipulate vector graphics.
It allows you to draw:
- shapes,
- text,
- images,
- or even animations directly in a web page.
Unlike the <canvas>
tag, SVG elements remain editable after their creation.
SVG is based on an XML format, which means that each drawing element is part of the DOM and can be styled or manipulated with CSS and JavaScript.
Structure and syntax of the <svg>
tag
Structure
Here is an example of simple syntax for the <svg>
tag:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
In this example:
width
andheight
define the dimensions of the SVG area.xmlns
specifies the XML namespace required for SVG (a must-have!).<circle>
draws a blue circle centered at(100, 100)
with a radius of 50 pixels.
Here is a small example:
Example
Here is an example of a more complex drawing with SVG:
<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<rect x="10" y="10" width="100" height="50" fill="red" />
<circle cx="200" cy="50" r="40" fill="green" />
<line x1="10" y1="150" x2="290" y2="150" stroke="blue" stroke-width="4" />
<text x="150" y="180" font-size="16" text-anchor="middle" fill="black">Example SVG</text>
</svg>
In this example:
<rect>
draws a red rectangle.<circle>
creates a green circle.<line>
draws a blue line with a stroke width of 4 pixels.<text>
displays the text "Example SVG" centered.
Try it yourself:
Attributes
The <svg>
tag accepts several attributes allowing you to define its dimensions and behavior:
width
: width of the SVG area;height
: height of the SVG area;viewBox
: defines a coordinate view to redimension the content proportionally;xmlns
: specifies the XML namespace (mandatory).
Use the
viewBox
attribute as much as possible to make the graphic responsive! 😉
Difference between <svg>
and <canvas>
Here is a quick comparison between these two tags:
Aspect | <svg> | <canvas> |
---|---|---|
Format | Vector graphics (XML) | Raster graphics (bitmap) |
Editability | The elements remain editable after their creation | Once drawn, the pixels are no longer individually modifiable |
Performance | Ideal for simple or interactive graphics (or logos) | Better for complex animations and drawings |
Manipulation | Each element is part of the DOM and can be manipulated with CSS/JS | Manipulations are done only with the drawing context |
Best practices
Here are some tips when using this tag:
- Use relative dimensions with
viewBox
to make your graphics responsive. - Organize your elements into
<g>
(groups) to simplify their manipulation (this avoids generality the generators of SVG images offer it by default).
For complex animations, use the
animate
properties or libraries like D3.js.
Browser compatibility
The <svg>
tag is widely supported by modern browsers:
Browser | Compatibility |
---|---|
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Internet Explorer | Partial (IE 9+) |