htmlsvg

Reuse SVG elements with different path values


I need to make circle sectors like shown here , however i'd like to define the sector svg once and then reuse it with different values for d in path. Something like

<svg>
   <defs id="circle>
      <g>
         <circle cx="115" cy="115" r="110"></circle>
         <path d="M115,115 L115,5 A110,110 1 0,1 225,115 z"></path>
         <circle cx="115" cy="115" r="50"></circle>
      </g>
   </defs>
</svg>

<svg>
    <use d="M115,115 L115,5 A110,110 1 0,1 115,125 A110,110 1 0,1 35,190 z" xlink:href = "#circle"/>
</svg>
<svg>
     <use d="M115,115 L115,5 A110,110 1 0,1 115,225 A110,110 1 0,1 35,190 z" xlink:href = "#circle"/>
</svg>

Is this possible?


Solution

  • You can't quite do it like that, but if you're willing to consider other options here's a way to get a similar visual result:

    <svg class="pie">
        <defs>
            <g id="pie">
                <circle cx="115" cy="115" r="80" stroke-dasharray="none"/>
                <path id="p" transform="rotate(90, 115, 115)" d="
                    M 115, 115
                    m -80, 0
                    a 80,80 0 1,0 160,0
                    a 80,80 0 1,0 -160,0
                    " />
            </g>
        </defs>
        <use xlink:href="#pie" stroke-dashoffset="52"/>
    </svg>
    <svg class="pie">
        <use xlink:href="#pie" stroke-dashoffset="125.5"/>
    </svg>
    <svg class="pie">
        <use xlink:href="#pie" stroke-dashoffset="300"/>
    </svg>
    

    See fiddle or this page. You could also use CSS for setting the stroke-dashoffset values on the <use> elements.

    In my example each pie diagram is also transparent in the middle, as you can see from the lime green page background. The rotate transform on the path is there to get the start of the stroke to begin at 12 o'clock.