SVG is an XML standard for Scalable Vector Graphics which is to say that images created in SVG can be scaled and rotated and manipulated. In addition each element in a SVG image is an element in the DOM. SO it is possible to say create a circle in SVG that can have standard JavaScript event handlers attached to it. Elements in SVG can also be manipulated as parts of the DOM, elements can be added, removed, or changed directly with the DOM or with jQuery. SVG elements can also be styled with CSS like any other HTML element.
Drawing in SVG is easier than drawing a circle with canvas.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400"> <circle cx="50" cy="50" r="25" fill="red"/> </svg>
The viewBox
attribute defines the starting location, width, and height of the SVG image.
The circle element defines a circle, with cx and cy the X and Y coordinates of the center of the circle. The radius is represented by r, while fill is for the fill style.
To view an SVG file, you simply open it via the File menu in any browser that supports SVG.
We can also draw rectangles in SVG, and add a stroke to them, as we did with canvas. This time, let’s take advantage of SVG being an XML—and thus text-based—file format, and utilize the desc tag, which allows us to provide a description for the image we’re going to draw.
<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 400 400"> <desc>Drawing a rectangle</desc> </svg>
Next, we populate the rect tag with a number of attributes that describe the rectangle. This includes the X and Y coordinate where the rectangle should be drawn, the width and height of the rectangle, the fill, the stroke, and the width of the stroke.
<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 400 400"> <desc>Drawing a rectangle</desc> <rect x="10" y="10" width="100" height="100" fill="blue" stroke="red" stroke-width="3" /> </svg>
It’s not always this easy. If you want to create complex shapes, the code begins to look complex.
--To save ourselves some work (and sanity), instead of creating SVG images by hand, we can use an image editor to help. One open source tool that you can use to make SVG images is Inkscape. Inkscape is an open source vector graphics editor that outputs SVG. Inkscape is available for download at http://inkscape.org/.
Raphaël is an open source JavaScript library that wraps around SVG. It makes drawing and animating with SVG much easier than with SVG alone. (http://raphaeljs.com/)