2014-12-08 109 views
0

下面是一些d3.js打造的正方形格子:陣列矩形的不d3.js

for (i = 0; i < N; i++){ 
    for (j = 0; j < N; j++){ 
     d3.select("#board") 
     .append("rect") 
     .attr("x", 10 + 60*i) 
     .attr("y", 10 + 60*j) 
     .attr("width", 50) 
     .attr("height",50); 
    } 
} 

我怎麼直接繪製<rect>元素與svg

回答

2

你的意思是沒有d3?使用DOM,像這樣......

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); 
rect.setAttribute("x", 10); 
... 

或標記

<rect x="<some number>" y="<some other number>" .../> 
0

如果你想很多相同的對象,你可以使用<use>標籤來創建在<defs>提到對象的副本部分。這使您不必重複所有的演示文稿屬性(width,height,fill等)。

<svg viewBow="0 0 400 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
 
    <defs> 
 
    <rect id="square" width="40" height="40" fill="#ff0" stroke="#f60" stroke-width="5" /> 
 
    </defs> 
 
    <!-- Create as many rectangles as you need: --> 
 
    <use x="5" y="5" xlink:href="#square" /> 
 
    <use x="55" y="5" xlink:href="#square" /> 
 
    <use x="105" y="5" xlink:href="#square" /> 
 
    <use x="155" y="5" xlink:href="#square" /> 
 
    <use x="205" y="5" xlink:href="#square" /> 
 
    <use x="255" y="5" xlink:href="#square" /> 
 
    <use x="305" y="5" xlink:href="#square" /> 
 
    <use x="355" y="5" xlink:href="#square" /> 
 
    <use x="5" y="55" xlink:href="#square" /> 
 
    <use x="55" y="55" xlink:href="#square" /> 
 
    <use x="105" y="55" xlink:href="#square" /> 
 
    <use x="155" y="55" xlink:href="#square" /> 
 
    <use x="205" y="55" xlink:href="#square" /> 
 
    <use x="255" y="55" xlink:href="#square" /> 
 
    <use x="305" y="55" xlink:href="#square" /> 
 
    <use x="455" y="55" xlink:href="#square" /> 
 
</svg>

+0

這是對內存/性能相當沉重,除非你特別需要一個更新主更新所有引用的功能。 – 2014-12-08 08:30:10

+0

@RobertLongson取決於你想要多少個矩形,我想。如果「直接使用SVG」意味着「使用Javascript」,我可能會用你的答案。 – 2014-12-08 11:59:12