[D3] SVG Group Element

結構部份:

<svg ...>
  <g></g>
</svg>

有 2 個理由需要使用 group element:

  • Grouping
  • Transformation

Group Element 裡面也可以有 Group Element:

<svg ...>
  <g>
    <g></g>
  </g>
</svg>

範例1:

<svg width="200" height="200">
      <g fill="purple">
        <circle cx="20" cy="20" r="20" />
        <circle cx="70" cy="70" r="20" />
      </g>
      <g>
        <rect x="110" y="110" height="30" width="30" />
        <rect x="160" y="160" height="30" width="30" />
      </g>
    </svg>

SVG Group Element Transformation

<svg ...>
  <g transform="...">
  </g>
</svg>

範例1:(向右移動 20units)

<svg width="200" height="200">
      <g transform="translate(20,0)">
        <circle cx="50" cy="50" r="20" />
      </g>
    </svg>

範例2:

<svg width="200" height="200">
      <circle id="outside" cx="40" cy="40" r="10" fill="green" />
      <g transform="translate(10,10)">
        <circle id="inside" cx="40" cy="40" r="10" fill="blue" />
      </g>
    </svg>
 

Grouping SVG Elements with D3

var svgSelection = d3.select("body").append("svg").attr("width", "200").attr("height", "200");

var groupSelection = svgSelection.append("g");
groupSelection.append("circle").attr("cx", 20).attr("cy", 20).attr("r", 20);
groupSelection.append("circle").attr("cx", 70).attr("cy", 70).attr("r", 20);

svgSelection.append("rect").attr("x", 110).attr("y", 110).attr("height", 30).attr("width", 30);
svgSelection.append("rect").attr("x", 160).attr("y", 160).attr("height", 30).attr("width", 30);

groupSelection.attr("fill", "purple");

D3 and SVG Group Element Transform

groupSelection.attr("transform", "translate(10, 20)");

// 動態
.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

您可在此處留言

avatar

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

  Subscribe  
Notify of