2012年12月3日月曜日

How to Include Scalable Vector Graphics (SVG) In-line

Now that Firefox 1.5 is out with support for SVG (Scalable Vector Graphics) included by default, and the same coming for Safari, perhaps some of us might want to actually useSVG for something.

Of course, Firefox 1.5 still represents a small minority of web users. Unless your application is somehow limited to this small slice of internet users, you can't really useSVG in-line unless you can have a safe fall-back for browsers that don't (yet) supportSVG.

It turns out this is relatively easy to do. It turns out the <object> tag can help us out.

The Code

The object tag is like a more generic version of the img tag. Rather than include images, it can include all kinds of objects (hence the name). You may have seen it in use to include Flash or Audio/Video content into a web page.

For a simple test case, let's imagine we want to include an SVG image on a page. However, for browsers that don't support SVG inline and don't have an SVG plug-in installed, we want to show them a simple PNG image instead.

The XHTML code is simple:

<object data="image-svg.svg" type="image/svg+xml" height="48" width="48"> <img src="image-png.png" height="48" width="48" alt="this is a PNG" /> </object>

The object tells the browser that it's including an SVG object (type="image/svg+xml") and points to the SVG file (data="image-svg.svg").

Contents of the object tag are used as alternate content if the object cannot be displayed. Think of what lives inside of the opening and closing object tags like "alt" text on an img tag. However, rather than a simple text alternative, we can include more XHTML.

In this case, we're including the familiar img and displaying a normal PNG image.

Browser Support (and the lack thereof)

This technique seems to be relatively well supported in the more popular web browsers. The browsers that support SVG (only Firefox 1.5, or other browsers with the Adobe SVG Viewer plug-in installed, so far), and other browsers degrade nicely and show the alternative content (a PNG in our test case). The only unfortunate display side-effect is that Firefox 1.0.x displays an addition plug-in notice at the top of the page (screenshot). This table shows the support in various browsers:

Firefox 1.0.x Displays PNG and Plug-In Notice (screenshot)
Firefox 1.5 Displays SVG
Safari Displays PNG
Internet Explorer Displays PNG
Why Would I Want To Do This?

A situation in which you might want to use SVG inline on a website is a bit difficult to imagine right now. The reason I looked into this was for a site where we want to display SVG graphics to show off that they are actually graphics created using SVG - not the most common or practical case. That said, we have to start somewhere.

I'm sure I've made some mistakes here. Feel free to post corrections or additions in the replies to this post.

0 件のコメント:

コメントを投稿