SVG: About using <defs> and <use> with variable text values

Posted by Lukman on Stack Overflow See other posts from Stack Overflow or by Lukman
Published on 2009-09-14T15:20:33Z Indexed on 2010/05/09 8:18 UTC
Read the original article Hit count: 280

Filed under:

Hi,

I have the following SVG source code that generates a number of boxes with texts:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
       "http://www.w3.org/TR/2001/REC-SVG-20050904/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
  <defs>
  </defs>
  <title>Draw</title>
  <g transform="translate(50,40)">
    <rect width="80" height="30" x="0" y="-20" style="stroke: black; stroke-opacity: 1; stroke-width: 1; fill: #9dc2de" />
    <text text-anchor="middle" x="40">Text</text>
  </g>
  <g transform="translate(150,40)">
    <rect width="80" height="30" x="0" y="-20" style="stroke: black; stroke-opacity: 1; stroke-width: 1; fill: #9dc2de" />
    <text text-anchor="middle" x="40">Text 2</text>
  </g>
  <g transform="translate(250,40)">
    <rect width="80" height="30" x="0" y="-20" style="stroke: black; stroke-opacity: 1; stroke-width: 1; fill: #9dc2de" />
    <text text-anchor="middle" x="40">Text 3</text>
  </g>
</svg>

As you can see, I repeated the <g></g> three times to get three such boxes, when SVG has <defs> and <use> elements that allow reusing elements using id references instead of repeating their definitions. Something like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
       "http://www.w3.org/TR/2001/REC-SVG-20050904/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
  <defs>
    <marker style="overflow:visible;fill:inherit;stroke:inherit"
            id="Arrow1Mend" refX="0.0" refY="0.0" orient="auto">
      <path transform="scale(0.4) rotate(180) translate(20,0)"
            style="fill-rule:evenodd;stroke-width:2.0pt;marker-start:none;"
            d="M 0.0,-15.0 L -20.5,0.0 L 0.0,15.0 "/>
    </marker>
      <line marker-end="url(#Arrow1Mend)" id="systemthread" x1="40" y1="10" x2="40" y2="410" style="stroke: black; stroke-dasharray: 5, 5; stroke-width: 1; "/>
  </defs>
  <title>Draw</title>
  <use xlink:href="#systemthread" transform="translate(50,40)" />
  <use xlink:href="#systemthread" transform="translate(150,40)" />
  <use xlink:href="#systemthread" transform="translate(250,40)" />
</svg>

Unfortunately I can't do this with the first SVG code since I need the texts to be different for each box, while the <use> tag simply duplicates 100% what's defined in <defs>.

Is there any way to use <defs> and <use> with some kind of parameters/arguments mechanism like function calls?

© Stack Overflow or respective owner

Related posts about svg