Chapter 12. Dynamic SVG and canvas

If all we needed was a way to create an image to add to a web page, we have paint programs and photo editors, and wouldn't need either an XML schema or scripted object: we'd just create the image, link it into our pages, and go happily on our way.

In earlier chapters, I introduced both SVG and the canvas element, but only static variations. The real power to both graphics systems is the fact that graphics can be created and modified dynamically, responding to a reader's interactions, a changing environment, or even new data.

The canvas object is already dependent on scripting, but adding interactivity to the element adds a new dimension of usefulness and interest. SVG, though, is as static as any web page in HTML or JPEG photo. Or is it?

SVG can be animated in two ways. The first is through the use of specialized animating elements that don't require scripting in any form in order to scale, fade, color, or move. The second form of SVG interactivity and animation occurs through the use of JavaScript and scripting.

Scripting can be added directly into the svg element, or the element can be accessed by a code block external to the element. Which is the better approach—embedded in the script or accessing the SVG externally—depends on whether the SVG is added to a web page from a file or added directly into the page.

Tip

This chapter uses the Document Object Model (DOM) methods, introduced in Chapter 10. If you've not worked with the DOM previously, you'll ...

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.