- 
                Notifications
    You must be signed in to change notification settings 
- Fork 9
Adding SVG elements
Assuming you have created an SVG object called svg (see here for details), you can add elements like this:
svg.add('rect', {'x': 10, 'y': 20, 'width': 80, 'height': 55, 'fill': 'blue'})
This will create a rect element in the SVG like this:
 <rect y="10" x="10" height="55" fill="blue" width="80"/>
Note that attributes are stored in a hash so will be in a random order.
The type of element created is determined by the first value passed to the svg.add() method. You can create elements of any type, regardless of whether they are valid SVG elements. In addition to svg.add(), there is svg.addChildElement() which does exactly the same thing, but requires more typing and is now deprecated.
The svg.add() method returns an SVGElement object which allows you to change its attributes. For example:
rect = svg.add('rect', {'x': 10, 'y': 20, 'width': 80, 'height': 55})
rect.attributes['fill'] = 'blue'
This way of altering attributes is exactly the same to how the SVG object's attributes are altered because the SVG object is itself a type of SVGElement object.
To add children to elements use the add() method:
group_element = svg.add('g')
group_element.add('rect', {'x': 10, 'y': 20, 'width': 80, 'height': 55})
This will create an SVG that looks like this:
<svg version="1.1" baseProfile="full" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
    <g>
        <rect y="10" x="10" height="55" width="80"/>
    </g>
</svg>
To create a text element containing the text "Hello world" pass the text at the third argument:
text = svg.add('text', {'x': 10, 'y': 20}, "Hello world")
Text can also be added at a later date using by appending text to an element's children:
text = svg.add('text', {'x': 10, 'y': 20})
text.children.append("Hello world")
Text can be added to any element type, but doesn't normally have an effect unless it is a text or tspan element. However this can be used to add comments into elements, for example:
svg.add('rect', {'x': 10, 'y': 20, 'width': 80, 'height': 55}, "<!-- Comment -->")
This will create an element containing a comment like this:
<rect y="20" x="10" height="55" width="80"><!-- Comment --></rect>
Text data is passed as the parameter child:
svg.add('g', child = "<!-- An empty group -->")