Chapter 15. Working with Media
Pretty pictures. Animations. Cool videos. Sound!
The web is a richer place through the availability of many media types. Our old friends SVG and Canvas can be used for complex animations, charts, and graphs. Added to them are the video and audio elements included in HTML5, and the near-future potential of 3D graphics.
Best of all, none of these require any kind of proprietary plug-in—they’re all integrated with all your browser clients, including those on your smartphones, tablets, and computers.
Adding JavaScript to SVG
Problem
You want to add JavaScript to an SVG file or element.
Solution
JavaScript in SVG is included in script elements, just as with HTML, except with the addition of CDATA markup surrounding the script (Example 15-1). DOM methods are also available for working with the SVG elements.
Example 15-1. Demonstration of JavaScript within an SVG file
<?xml version="1.0" encoding="UTF-8" standalone="no"?><svgxmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"width="600"height="600"><scripttype="text/ecmascript"><![CDATA[// set element onclick event handlerwindow.onload=function(){constsquare=document.getElementById('square');// onclick event handler, change circle radiussquare.onclick=functionclick(){constcolor=this.getAttribute('fill');if(color==='#ff0000'){this.setAttribute('fill','#0000ff');}else{this.setAttribute('fill','#ff0000');}};};]]></script><rectid=