SVGGraph using SVG elements in HTML5 or XHTML documents
As well as the
object methods for including an SVG inside a page
(please read the Using SVGGraph page for
details), all the major browsers now support directly including SVG graphics
inside HTML documents. This means fewer requests are made to the server, so it
can make pages containing SVG load a lot quicker. IE 9 is the first version of
Internet Explorer to support displaying SVGs this way, though FireFox, Chrome,
Safari and Opera have all supported it for a while.
Depending on the standard used by your website, there are two ways to make it work:
SVG in HTML5
Below is a full working example of embedding two SVG bar graphs in an HTML5 page. The constructor is only called once, with a width of 400 pixels, a height of 300 pixels and no user settings, so both graphs will be the same size and use the default random colours.
Fetch() function is used to generate the SVG
content instead of
content-type header and everything needed to serve
an SVG directly to the browser - we don't want it to do that in this case,
which is why we are using
The first argument to
Fetch() is the graph type, and the
false to prevent outputting the XML declaration
and doctype. The function also has a third, optional argument that can
Because we have two graphs on one page, we don't want to duplicate
both graphs is output in one block using the
function. Since we are using all default options, this means that the code
to show the tooltips (which are enabled by default) will be in this block of
</script> tags - unless
which case the function will return an empty string.
Of course, since they all return strings you can output the results in
whichever order you want, but they must be called in the correct order.
SVG in XHTML
XHTML is the older, strict XML-based version of HTML from before HTML5
became available. SVG is also XML-based, so embedding one in the other is
really just a case of using the correct
Below is the same example as above, adjusted to produce valid XHTML.
The HTML body of the page and the PHP used there are exactly the same in
both examples - the differences are at the top of the file. First, the PHP
header() function sets the
content-type for XHTML
The next change is that a settings array has been passed to the SVGGraph
constuctor, setting the
namespace option to
This tells SVGGraph to use the
svg: namespace in front of every
SVG tag that it outputs. (
The doctype has changed to the correct value for the W3C XHTML / MathML /
SVG profile, and the opening
<html> tag now includes the
XHTML, SVG and XLink namespaces. Finally, the
content-type specified in the HTTP header.
CSS with SVG in HTML
CSS in your HTML page stylesheet can affect the content of SVG within the
page. SVGGraph generally uses SVG attributes to set font styles, etc.
font-size="10", for example) so CSS rules can easily take
precedence over values set in the SVGGraph options.