Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating a SVG path

Say that I have the following arrow, which I want to repeat several times at different locations within the svg:

<svg width="400" height="400">
<path transform="translate(150,100)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" />
<path transform="translate(300,200)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" />
<path transform="translate(150,300)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" />
</svg>

arrows

I might want to change the path shape in the future, so I would prefer to avoid copy-pasting the d attribute all over the place.

Is it possible to define path's shape somewhere and then place it at different x, y coordinates, without manipulating it from javascript?

Two thoughts:

  • d is an attribute, not a property, so we cannot use CSS AFAIK
  • <defs> does not seem to support paths

Is there any way to avoid copy past the entire thing, short of injecting it from javascript?

like image 212
Ricardo Magalhães Cruz Avatar asked Dec 07 '22 23:12

Ricardo Magalhães Cruz


1 Answers

This answer provided as an extension to JCD's answer in order to show OP what I by the <symbol> not being required here. <symbol> elements provide some features that are not needed when you are simply reusing an element.

<svg width="400" height="400">
  <defs>
    <path id="mypath" fill="black" d="M 0,20 l25,20 100,0 0,-40 -100,0 z" />
  </defs>
  <use xlink:href="#mypath" x="50" y="100" />
  <use xlink:href="#mypath" x="200" y="200" />
  <use xlink:href="#mypath" x="50" y="300" />
</svg>
like image 95
Paul LeBeau Avatar answered Dec 11 '22 12:12

Paul LeBeau