Chapter 18 Drawing on Demand: Interactive SVG
This chapter explores the potential for using SVG in interactive web content. It is not in any way a comprehensive discussion of the topic: interactive SVG is as complex a topic as interactive HTML. We cover the main ways in which you can enable and react to user actions—what you do with that is up to you. Interactive SVG can be used in web application interfaces, games, and explorable data visualizations, among many other possibilities.
As we’ve mentioned various times throughout the book, the capabilities of SVG differ depending on how you add that SVG to your HTML. If you use an SVG file as an image, in an
<img> tag or as a CSS image type, it will behave as an image. None of the components will be interactive.
To add interactive SVG to a web page, you need to either use inline SVG markup or embedded SVG objects (with
<iframe>). Alternatively (and especially for testing), you can open the SVG files directly as the main web page—which becomes much more practical once you include links from that SVG web page to other pages on the web.
Figures and Examples#
The file names link to the code view on GitHub. Beware: the linked screenshots are hi-resolution; some have very large file sizes.
View all files for this chapter on GitHub.
- Figure 18-1. Links in SVG text used as website navigation
- Example 18-1. Adding hyperlinks to SVG text layouts
- Figure 18-2. The photograph to use in the image map
- Figure 18-3. The final result, when one link is focused
- Example 18-2. Creating an interactive image map with SVG links and clipping paths
- Figure 18-4. The hoverable shapes, with the second circle hovered
- Example 18-3. Maintaining predictable hover regions despite changing strokes
- Figure 18-5. An interactive SVG style sample, after the first link has been activated (but the second link is focused)
- Example 18-4. Using same-page links and
:targetto create a style switch
- Figure 18-6. An SVG game using click events on colored circles
- Figure 18-7. A completed version of the confetti game
- Figure 18-8. An SVG game using click events on colored gems made from
- Figure 18-9. A game with additional elements added based on mouse-click positions
- Example 18-6. Creating new elements when click events do not hit a target
- A variation on the gem-click game with moving gems (created but not used for the Chapter 19 section on scripted animation)
- Figure 18-X1. A custom SVG checkbox in an HTML form
- Example 18-X1. Creating a custom checkbox with hidden HTML, inline SVG, and CSS pseudoclasses
- Figure 18-X2. Inline SVG controlled by hidden HTML radio buttons
- Example 18-X2. Using HTML radio buttons and
:checkedto create an SVG style switch