apike.ca

Nested SVG Tags

By mbystedt on Feb 24, 2014, 10:35:00 PM

Another way to use the 'svg' element is to create additional drawing areas in a SVG document. Why would you want to do that? So you can change the view box to suit your needs. Consider a SVG document which shows a mathematical graph inside it. It is highly unlikely that the coordinates used for the graph and the SVG document match. This new view box can match the mathematical graph and be placed into the SVG document.

Example 1. An SVG fragment inside a document. (Download)
    <text x="10" y="191">Function: sin(x)*x</text>
 
    <!-- The inner svg fragment -->
    <svg id="innerSVG" onload="makeGraph(evt)" x="10" y="10"
        width="170" height="170"
        viewBox="-50 -50 100 100">
    ...
    </svg>
Code 1. Nested SVG fragment with more convenient coordinates.

This element creates an SVG document fragment. SVG documents are self-contained XML documents with one SVG document fragment and zero or more SVG elements placed inside. SVG document fragments can be placed inside of other SVG document fragments. This creates a new view box and all objects placed inside it use the new coordinates created by it.

By using a SVG tag, you can create a rectangular mask as (by default) everything outside the viewing space is clipped away. Adding 'overflow="visible"' to a svg tag disables this mask.

One snag to using an inner SVG document to change the coordinate system is that it's really a transformation. So, you'll end up with squished strokes and eclipse-like circles if the inner coordinates are not square.

Related Topics