2013-11-21 15 views
0

下面的代碼將繪製48個正方形,其中包含0到47之間的數字 我已經閱讀了stackoverflow,使用sets是最好的方法來做到這一點,因爲我將矩形形狀與其文本編號分組在一起,所以我可以參考他們都與location 我有很多位置,所以我想把它們放在名爲locations的數組中。
locations[]數組因此是一個矩形列表(其本身是集合),其中包含一個數字。如何在Raphael中創建一組數組?

window.onload = function() { 
var paper = new Raphael(document.getElementById('canvas_container'), 1200, 1000); 
var locations = []; 
var location = paper.set(); 

//squares have same width and height. 
var width = 12; 

// draw 48 locations 
for (i=0; i<48;i++) { 
    location.push(paper.rect(width*(i+1),10, width, width)); 
    location.push(paper.text(width*(i+1)+(width/2),width+(width/3),i).attr({ "font-size": 8, "font-family": "Arial, Helvetica, sans-serif" })); 

    locations[i] = location; 
    location.length = 0; //clears the set 
} 

//locations[9].translate(Math.random() * 350, Math.random() * 380); 

} 

問題是最後一行。如果我取消註釋,所有48個盒子將被翻譯並一起移動。 我想要做的就是移動第10平方米。
我顯然做錯了我的數組和我如何填充他們,但我不知道。

+0

'for'循環的最後一行沒有多大幫助。你已經建立了'locations'數組,其中每個項目包含2 * 48個元素(矩形和文本)。你可以用'console.log(locations [0]);''因爲那個'transform'移動了所有東西。 –

回答

0

for循環的最後一行沒有清除集合。您已經構建了位置數組,其中每個項目包含2 * 48個元素(矩形和文本)。你可以看到console.log(locations[0]);因爲這個變換將四處移動。

Rearanged使得每個數組項只包含一個對(RECT,文本):

window.onload = function() { 

var paper = new Raphael('canvas_container', 1200, 1000); 
var locations = []; 
var location = paper.set(); 

function Item(elem, text) { 
    this.elem = elem; 
    this.text = text; 
} 

//squares have same width and height. 
var width = 12; 

var item; 

for (var i = 0; i < 5; i++) { 

    item = new Item(
      paper.rect(width * (i+1), 10, width, width), 
      paper.text(width * (i+1) + (width/2), width + (width/3), i).attr({ "font-size": 8, "font-family": "Arial, Helvetica, sans-serif" }) 
     ); 

    locations[i] = item; 
} 

location = paper.set(); 
location.push(locations[3].elem); 
location.push(locations[3].text); 

location.translate(Math.random() * 350, Math.random() * 380); 

} 

Demo at fiddleupdate與隨機選擇。