Learning Basic Animation Using HTML5 and SVG

HTML5 has some animation capabilities when used in conjunction with a Javascript library, but to get the most out of an app with animations, Scalable Vector Graphics (SVG) language can bring the capabilities of two-dimensional graphics and graphic apps in XML to the table. Most of the browsers in heavy use today, with the notable exception of versions of Internet Explorer preceding IE 9, offer good support for SVG.

Incorporating SVG in HTML5

Inlining is the most common way to include SVG code into HTML5, but most types of inclusion will work. These methods include copying and pasting SVG code in HTML (inlining), using the HTML img tag, use of the HTML iframe tag, use of the HTML object tag, and by using Cascading Style Sheets (CSS). Once that is done, you will need to adapt the size of the embedded images(s).

Manipulating the Size and Position of SVG Graphics

There are several good ways to get this job done. One of the best methods for static images is to fix the graphic with a viewbox and size attributes. Then, the developer must import it with the HTML img tag.

svg

xmlns="http://www.w1.org/2000/svg"

version="1.1"

width="100%"

height="100%"

viewBox="0 0 684 648">

The height can then be set in the HTML code:

<img src="pineapple.svg" height="100" alt="Nice pineapple tree"/>

Using the SVG Transform Attribute to Change Graphic Size

To change the size of a graphic, edit the SVG file by adding the following code after the opening SVG tag:

<g transform="scale(0.1)">

Add the following before the SVG closing tag:

</g>

This is a good method to use with SVG graphics in order to adapt the size of various parts. You must remember to wrap it inside a g transform=”scale(....)”. This may not be the most elegant of solutions, but it does work.

Using the SVG image Tag to Import and Size a SVG Graphic

This is an example of a more elegant method that will work on all browsers. Here is how one uses the SVG image tag.

<html>

<head>

<title>HTML5 SVG demo</title>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

</head>

<body>

<h1>HTML5 SVG Demon stration - embed svg file with SVG image</h1>

<p> A large red circle that was embedded using the svg "image" tag:</p>

All you have to do here is to figure out the proportions of the original SVG by looking at the root elements of the file, and define the width and the height of the image and scale it to your needs for the app. In this example, where the dimensions of the imported graphic is 600 pixels X 600 pixels, if you wanted to scale it down by a factor of 10 you would need to divide x and y by 10.

To learn more about the ins and outs of this subject, you will need to dive deep into the image element, and learn more about the view box.