Reusing elements with 'defs' and 'use'


In the next example, I've used a defs element to define the shapes before they're rendered. To understand how it works, just look at the line <circle id="s1"...

We've defined the circle in the same way as we've done earlier, but the id attribute gives it a name. Later on, I can use the id that I've assigned here. In this case I just want to draw them, so I can do that with a 'use' element. That element takes the id as the value for the xlink:href attribute (look down a little further in the source to the line with xlink:href="#s1"). The x and y attributes of the 'use' element get added to those in the original definition (that is, the cx and cy of the circle in this case). I use the 'defs' and 'use' as a convenience in some of the later examples. The usage here is pretty simple, so if you want the details of how they work, look at the w3c specification entries for the use element and the defs element.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "">

<svg viewBox = "0 0 1000 1000" version = "1.1">
        <!-- A circle of radius 200 -->
        <circle id = "s1" cx = "200" cy = "200" r = "200" fill = "yellow" stroke = "black" stroke-width = "3"/>
        <!-- An ellipse (rx=200,ry=150) -->
        <ellipse id = "s2" cx = "200" cy = "150" rx = "200" ry = "150" fill = "salmon" stroke = "black" stroke-width = "3"/>
    <use x = "100" y = "100" xlink:href = "#s1"/>
    <use x = "100" y = "650" xlink:href = "#s2"/>
©2004 Late Night PC Service | About Us | Site Map | Contact Us