Set X and Y value for g element of SVG

前端 未结 1 1752
孤街浪徒
孤街浪徒 2021-01-12 15:22

I am relatively new in SVG drawing with HTML5.

What I want to do is to make a group of elements in SVG with g element so that all e

相关标签:
1条回答
  • 2021-01-12 15:45

    <g> elements don't support x or y attributes. You can use a transform instead though.

    I've decreased the values from 1000 to 100 as otherwise the output is outside the 500 x 300 canvas of the outer <svg> element.

    I've provided additional x and y attributes on the text element so it appears positioned as in your example. If wanted you could put the text itself in a <g> element or an <svg> element.

    <svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
      <g transform="translate(100, 100)">
        <title>SVG Title Demo example</title>
        <rect width="200" height="50"
        style="fill:wheat; stroke:blue; stroke-width:1px"/>
        <text x="100" y="30" style="text-anchor: middle;" class="small">My Text</text>
      </g>
    </svg>

    or using an additional <g> element to avoid x and y on the text itself.

    <svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
      <g transform="translate(100, 100)">
        <title>SVG Title Demo example</title>
        <rect width="200" height="50"
        style="fill:wheat; stroke:blue; stroke-width:1px"/>
        <g transform="translate(100, 30)">
            <text style="text-anchor: middle;" class="small">My Text</text>
        </g>
      </g>
    </svg>

    Alternatively you could use an inner <svg> element instead of a <g> element as that does support x and y attributes

    <svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
      <svg x="100" y="100">
        <title>SVG Title Demo example</title>
        <rect width="200" height="50"
        style="fill:wheat; stroke:blue; stroke-width:1px"/>
        <text x="100" y="30" style="text-anchor: middle;" class="small">My Text</text>
      </svg>
    </svg>

    0 讨论(0)
提交回复
热议问题