Skip to main content

SVG (Scalable Vector Graphics)

SVG defines vector-based graphics in XML, which can be embedded directly in HTML pages. SVG graphics are scalable, so they do not lose quality when zoomed or resized, and SVG is supported by all major browsers.


What is SVG?

Key points about SVG: it stands for Scalable Vector Graphics; it is used to define vector-based graphics for the web; it defines graphics in XML format; each element and attribute can be animated; it is a PromptCookbook recommendation; and it integrates with other standards like CSS, DOM, XSL, and JavaScript.


The <svg> Element

The <svg> element is a container for SVG graphics. SVG has methods for drawing paths, rectangles, circles, polygons, text, and much more.

SVG Circle

A circle with a stroke and fill.

Prompt
A page with an SVG element (100x100) drawing a circle centered at (50,50) with radius 40, a green 4px stroke, and a yellow fill.
Output: complete HTML page

SVG Rectangle

A rectangle with a stroke and fill.

Prompt
A page with an SVG element (400x120) drawing a rectangle at (10,10), 200x100, with a red 6px stroke and a blue fill.
Output: complete HTML page

Rectangle with opacity and rounded corners

A rounded, semi-transparent rectangle.

Prompt
A page with an SVG element (400x180) drawing a rectangle with rounded corners (rx and ry 20), red fill, black 5px stroke, and 50% opacity, styled inline.
Output: complete HTML page

SVG Star

A five-point star drawn with a polygon.

Prompt
A page with an SVG element (300x200) drawing a five-point star polygon with a lime fill, purple 5px stroke, and the evenodd fill rule.
Output: complete HTML page

Gradient ellipse and text

An ellipse filled with a gradient, with text on top.

Prompt
A page with an SVG element (500x130) drawing an ellipse filled with a yellow-to-red linear gradient, plus the white text "SVG" over it, with a fallback message for browsers without inline SVG.
Output: complete HTML page

Differences Between SVG and Canvas

SVG is a language for describing 2D graphics in XML, while Canvas draws 2D graphics on the fly with JavaScript. Because SVG is XML based, every element is in the SVG DOM, so you can attach JavaScript event handlers to shapes. Each SVG shape is remembered as an object, so if its attributes change, the browser re-renders it automatically. Canvas, by contrast, is drawn pixel by pixel and forgets the graphic once drawn, so changing its position means redrawing the whole scene.


Comparison of SVG and Canvas

SVG is resolution independent, supports event handlers, has good text rendering, but can be slow with complex graphics and is not suited for games. Canvas is resolution dependent, has no event-handler support, has poor text rendering, lets you save the result as a .png or .jpg, and is well suited for graphic-intensive games.