Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)

   


Mouse Clicks and Resizing Circles

Consider the mouse-aware circle rendered in Figure 11.8.

Figure 11.8: A circle whose radius changes after a mouse click.

The SVG document resizeCircle1.svg in Listing 11.10 demonstrates how to use the SVG onclick element in order to resize a circle and change its color.

Listing 11.10 resizeCircle1.svg

<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"> <desc>Capture mouse click events</desc> <!-- script for updating the visible circle --> <script type="text/ecmascript"> <![CDATA[ function mouseClick1(evt) { var circle = evt.target; var currentRadius = circle.getAttribute("r");

Remarks

The logic for updating the circle rendered in Listing 11.10 is contained in the following ECMAScript function:

function mouseClick1(evt) { var circle = evt.target; var currentRadius = circle.getAttribute("r"); if(currentRadius == 100) { circle.setAttribute("r", currentRadius*2); circle.setAttribute("fill", "#FF0000"); } else { circle.setAttribute("r", currentRadius*0.5); circle.setAttribute("fill", "#FFFF00"); } }

When you click inside the circle, here's what happens: the variable circle is assigned a reference to the object representing the clicked circle, thereby allowing you to extract the value of the attribute r as shown below:

var circle = evt.target; var currentRadius = circle.getAttribute('r");

The 'if/else" logic in the ECMAScript code contains the logic for setting the new value for the r attribute (i.e., the radius of the circle) and the fill attribute of the circle.


   

Категории