HTML SVG
HTML SVG Graphics
SVG (Scalable Vector Graphics) is a vector-based graphics format defined in XML and can be embedded directly into HTML pages.
What Is SVG?
SVG stands for Scalable Vector Graphics. It is used to describe two-dimensional vector graphics for the web.
- SVG graphics are defined using XML
- They scale without losing quality when zoomed or resized
- Every SVG element can be styled and animated
- SVG is a W3C recommendation
- SVG integrates with CSS, DOM, and JavaScript
SVG is supported by all modern browsers.
The <svg> Element
The <svg> element acts as a container for SVG graphics.
SVG supports shapes such as paths, rectangles, circles, polygons, text, and gradients.
SVG Circle
A circle is created using the <circle> element.
<svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg>
SVG Rectangle
Rectangles are created using the <rect> element.
<svg width="400" height="120"> <rect x="10" y="10" width="200" height="100" stroke="red" stroke-width="6" fill="blue" /> </svg>
Rectangle with Rounded Corners and Opacity
The rx and ry attributes create rounded corners.
<svg width="400" height="180"> <rect x="50" y="20" rx="20" ry="20" width="150" height="150" style="fill:red;stroke:black;stroke-width:5;opacity:0.5" /> </svg>
SVG Polygon (Star)
The <polygon> element draws complex shapes using multiple points.
<svg width="300" height="200"> <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" /> </svg>
SVG Gradient, Ellipse, and Text
SVG supports gradients and text rendering inside graphics.
<svg width="500" height="130"> <defs> <linearGradient id="grad1"> <stop offset="0%" stop-color="yellow" /> <stop offset="100%" stop-color="red" /> </linearGradient> </defs> <ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" /> <text x="50" y="86" fill="#ffffff" font-size="45" font-family="Verdana">SVG</text> </svg>
SVG vs Canvas
SVG and Canvas are both used for drawing graphics, but they work very differently.
Key Differences
- SVG describes graphics using XML, Canvas draws graphics using JavaScript
- SVG elements exist in the DOM and support event handlers
- Canvas draws pixels and does not retain object information
- SVG automatically re-renders when attributes change
- Canvas must redraw the entire scene to reflect changes
Comparison of SVG and Canvas
- SVG: resolution independent, supports events, good text rendering, slower with very complex graphics
- Canvas: resolution dependent, no built-in events, faster for pixel-heavy graphics, suitable for games