What Are Nested SVG Canvases

Q

What Are Nested SVG Canvases?

✍: FYIcenter.com

A

Nested SVG Canvases are two canvases with one nested inside the other.

Remember that a SVG canvas is represented by a "svg" XML element. So the following XML document represents two nested SVG canvases:

<svg id="outer">
  <!-- objects on the outer canvas -->

  <svg id="inner" x="location_x" y="location_y">
    <!-- objects on the inner canvas -->
  </svg>
<svg>

The inner canvas is considered as a child graphical object of the outer canvas. It should have "x" and "y" attributes to specify the location of its top left corner on the outer canvas.

Here is an HTML document, nested-canvases.html, that has a SVG image with two nested canvases:

<html><body>
<svg xmlns="http://www.w3.org/2000/svg" 
  id="outer" style="background-color: #dddddd"
  width="200" height="200" viewBox="-50 -50 100 100">
  <line x1="-50" y1="0" x2="50" y2="0" stroke="black" stroke-dasharray="4"/>
  <line x1="0" y1="-50" x2="0" y2="50" stroke="black" stroke-dasharray="4"/>

  <line x1="-10" y1="-5" x2="-10" y2="-15" stroke="black" stroke-width="4"/>
  <line x1="10" y1="-5" x2="10" y2="-15" stroke="black" stroke-width="4"/>

  <svg id="inner"
    x="-25" y="0"
    width="50" height="25" viewBox="-50 0 100 50">
    <rect x="-50" y="0" width="100" height="50" fill="#ffdddd"/>

    <ellipse cx="0" cy="0" rx="50" ry="35" 
      stroke="blue" stroke-width="4" fill="none"/>
  </svg>
</svg>
</body></html>

When you open the above HTML file, nested-canvases.html, in a Web browser, you see a smiling emoji with mouth created in an inner canvas. Dash lines and background colors are added to help you identify the outer and inner canvases and their object coordinates.

Nested SVG Canvases
Nested SVG Canvases

As you can see from the above example, the main advantage of using an inner canvas is that you can have an independent Viewbox-Viewport mapping to create an image component. Then place it as a given location on the outer canvas.

Note that the "x" and "y" attributes on the outermost "svg" element are ignored, since there is no more outer canvas to locate this canvas.

 

Transformation of Object Coordinates

SVG "preserveAspectRatio" Attribute

SVG Coordinates, Size and Viewport

⇑⇑ SVG (Scalable Vector Graphics)

2023-02-03, 293🔥, 0💬