Canvas & SVG: Using SVG - JUMP START HTML5 (2014)

JUMP START HTML5 (2014)

Chapter 18 Canvas & SVG: Using SVG

In modern browsers, SVG can be used anywhere where you would normally use JPGs, GIFs or PNGs. Add to this the ability to add colors and gradients, plus the fact that you get no loss of quality when scaled, and it's something to get excited about for the majority of designers.

Inserting SVG Images on Your Pages

There are several ways to add SVG to your page:

· The object tag

· The embed tag

· Within an iFrame

· Using a CSS background

· Inline SVG embedded into your HTML5 page

· Using an img tag

Important: Use CSS for Repeating Backgrounds

Only CSS can be used for repeating backgrounds. The other methods will just show a single image.

Which Method Should You Use?

That will depend on the project at hand but, generally, object or embed should be used if you intend to use DOM scripting to manipulate the image in JavaScript. An iframe can be used for the same purpose although the code becomes a little more cumbersome. Alternatively, an inline SVG may be appropriate if you need scripting but the image is used on a single page on your website.

If you just need a static SVG, use the img tag or a CSS background. These do not permit the SVG to be modified on the client.

Important: SVG MIME type

Your web server should return SVG images with the MIME type image/svg+xml. Most servers should do this automatically, but double-check if images do not display correctly.

Let's have a look at how you'd go about it using the object method using an SVG file we created using an application such as Illustrator or Inkscape:

<object type="image/svg+xml"

↵width="400" height="400" data="image.svg">

</object>

An embed tag is similar, but embed only became standard in HTML5. It's possible some older browsers could ignore it, but most implement the tag:

<embed type="image/svg+xml"

↵width="400" height="400" src="image.svg">

</embed>

An iframe loads the SVG much like any other web page:

<iframe src="image.svg">

</iframe>

We've already used inline SVG images added directly to the HTML page. This does not incur additional HTTP requests but will only be practical for very small images or those you don't intend using elsewhere:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">

<circle id="redcircle" cx="100" cy="100" r="100" fill="red" />

</svg>

An img tag is identical to any you've used before:

<img src="image.svg" />

Finally, the CSS background-image property can reference an SVG:

#myelement {

background-image: url(image.svg);

}

SVG Tools and Libraries

There are many libraries, snippets and useful tools for creating and manipulating SVG images.

Snap SVG from Adobe is a free, open-source tool for generating interactive SVG.

Another great resource, Bonsai, provides a JavaScript library with snippets and demonstrations to help you alter SVG images using client-side code.