Animated Clock: The Hello World of Animated and Interactive SVG

Whatever you can do with a web page, you can do with an SVG document. Move elements about, change opacity, shrink, grow, or rotate. You can also create new elements to either replace existing elements or add new ones. If you don't want an element, remove it from the document.

Too many modifications to cover in-depth, but we can look at a few examples and see what kind of trouble we can generate.

The Dots, the Dots

I created a small application that does nothing more than add or remove dots from within an SVG canvas. I implemented it first as an HTML application using an object to hold an external SVG file, and then using inline SVG. How it works is that if you click on the SVG canvas area, a new randomly colored dot is added at that position. However, if you click on any existing circle, it's removed from the page. Simple, but it does demonstrate event handling, capturing mouse events in the SVG document, and adding and removing elements.

The SVG, whether inline or included through an object, is very simple:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
       width="600" height="600">
<circle id="redcircle" cx="30" cy="30" r="30" fill="red" />
</svg>

Example 12-10 has the contents of the application that uses the object element to embed an external SVG document.

Example 12-10. Dots application with SVG document as an external object

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ...

Get Painting the Web now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.