Understanding Scalable Vector Graphics (SVG)
SVG is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. Unlike raster graphics (like JPEGs or PNGs), SVG graphics are defined by mathematical equations that describe points, lines, and curves. This means they can be scaled infinitely without losing quality, making them perfect for web design, logos, icons, and complex illustrations.
Key Concepts in SVG
At its core, SVG defines graphics using a markup language. You can embed SVG directly into HTML or use it as a standalone file.
Basic Shapes
SVG provides several basic shape elements:
- `
`: Defines a circle. - `
`: Defines a rectangle. - `
`: Defines a line. - `
`: Defines a shape with a set of connected straight lines. - `
`: Defines a shape with a set of connected lines (similar to polygon but doesn't auto-close). - `
`: Defines an ellipse.
Example: A Simple Circle and Rectangle
This SVG contains a yellow circle with a purple border and a green rectangle with a black border.
<circle cx="50" cy="75" r="40" stroke="purple" stroke-width="4" fill="yellow" />
<rect x="120" y="30" width="60" height="90" style="fill:rgb(0,150,0);stroke:black;stroke-width:2;" />
</svg>
Paths
The most powerful element in SVG is the `
- M (moveto): Starts a new sub-path.
- L (lineto): Draws a straight line.
- H (horizontal lineto): Draws a horizontal line.
- V (vertical lineto): Draws a vertical line.
- C (curveto): Draws a cubic Bézier curve.
- S (smooth curveto): Draws a smooth cubic Bézier curve.
- Q (quadratic Bézier curveto): Draws a quadratic Bézier curve.
- T (smooth quadratic Bézier curveto): Draws a smooth quadratic Bézier curve.
- A (elliptical arc): Draws an elliptical arc.
- Z (closepath): Closes the current sub-path by drawing a straight line from the current point to the starting point of the sub-path.
Example: A Custom Path
This path defines a shape that starts at (10,10), goes to (90,10), curves to (90,90), then goes to (10,90), and finally closes the path. It's like a rounded rectangle with one side bowed out.
<path d="M10 10 L90 10 Q100 50 90 90 L10 90 Z" fill="orange" stroke="darkred" stroke-width="3" />
</svg>
Attributes
SVG elements have attributes that control their appearance and behavior. Common attributes include:
- `fill`: Sets the color used to fill the shape.
- `stroke`: Sets the color used to outline the shape.
- `stroke-width`: Sets the width of the outline.
- `opacity`: Sets the transparency of an element.
- `id`: Assigns a unique identifier to an element, useful for scripting or CSS.
Experiment with Fill and Stroke
Try changing the fill and stroke colors for a simple shape.
Exploring SVG opens up a world of possibilities for creating dynamic, scalable, and visually rich graphics on the web.
For more advanced topics like gradients, filters, animations, and interactivity, check out our Advanced SVG Techniques guide.