如何在拉斐尔中创建一组集合

How to create an array of sets in Raphael?

本文关键字:集合 一组 创建      更新时间:2023-09-26

下面的代码将绘制48个正方形,其中包含数字0到47我在stackoverflow上读到,使用集合是最好的方法,因为我将矩形及其文本编号分组在一起,这样我就可以用location引用它们我有很多位置,所以我想把它们放在名为locations的数组中
因此,locations[]数组是一个矩形列表(它们本身就是集合),其中包含一个数字。

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个广场
我显然对我的数组以及如何填充它们做了一些错误,但我不知道。

循环中的最后一行未清除集合。您已经构建了位置数组,其中每个项包含2*48个元素(rect和text)。你可以在console.log(locations[0]);中看到,因为变换会移动所有的东西。

重新排列,使每个数组项只包含一对(rect,text):

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);
}

随机选择演示和更新。