Firefox 3 – SVG foreignObject

SVG is a nice way to create vector graphics on the web and even embedded in HTML pages. Sometimes you might embed other markup into SVG and that’s where foreignObject comes in. From the W3 SVG1.1 spec:

The ‘foreignObject’ element allows for inclusion of a foreign namespace which has its graphical content drawn by a different user agent. The included foreign graphical content is subject to SVG transformations and compositing.

One of the most common uses (IMO) of using foreignObject is to embed HTML into SVG. The examples that come to mind are:

  • Using HTML to simplify text wrapping – SVG’s text wrapping abilities are far from convenient. Using tspan to create multiline text ranges is a pain. On the other hand, using an HTML p, div, or span is much easier. You also get list and formatting support. Here is an example of using HTML in SVG for text handling.
  • Using SVG transforms on HTML content – SVG’s transformation capabilities are fairly cool and can do things that HTML can’t. However, it is possible to use SVG transformations on a foreignObject that holds HTML. Here is an example of SVG transforming (rotating and translating) HTML content.

Note: These examples will only work in a recent Firefox 3 alpha (or any browser that supports SVG foreignObject). And yes, these examples could have been done as SVG embedded in HTML or XUL as well.

7 Replies to “Firefox 3 – SVG foreignObject”

  1. There are some caveats to using HTML text instead of SVG text.

    a) SVG text does not scale independently of the SVG image so if you increase or decrease the text size in the browser it has no effect on your SVG text. If you use HTML text however this will change size, possibly obscuring parts of your drawing.

    b) SVG text ignores the browser’s minimum font size. I.e. Tools->Options->Fonts & Colours(Advanced)->Minimum Font Size. If you have this set your HTML replacement text may come out bigger than you expect on your drawing.

  2. Well this is the first time I’ve filled out an HTML form on a 20 degree angle.

    Your first example was more interesting to me – seems like we can use SVG foreignObject to emulate rounded corners of divs or gradients on divs, etc. It’s unfortunate that Mozilla doesn’t support SVG as CSS background-image (which would probably be the preferred way). Opera 9.5 will be able to do this.

    So let’s say I want a div to have a gradient background with rounded corners – I’d like to use SVG to do this. Any thoughts of detecting capabilities across browser?

  3. Awesome the transforms. Some screens would be ok also 😉 to those that don’t want to download Firefox3.

Comments are closed.