【问题标题】:How to create an array of sets in Raphael?如何在 Raphael 中创建一组集合?
【发布时间】:2013-11-21 06:05:02
【问题描述】:

以下代码将绘制 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 个方格。
我显然对我的数组以及我如何填充它们做错了,但我不知道。

【问题讨论】:

  • for 循环中的最后一行没有多大帮助。您已经构建了 locations 数组,其中每个项目包含 2*48 元素(矩形和文本)。你可以看到console.log(locations[0]); 因为transform 移动所有东西。

标签: javascript jquery arrays raphael


【解决方案1】:

for 循环中的最后一行没有清除设置。您已经构建了位置数组,其中每个项目包含 2*48 元素(矩形和文本)。你可以通过console.log(locations[0]); 看到这一点,因为这个变换会移动所有东西。

重新排列,使每个数组项仅包含一对(矩形,文本):

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 fiddle 和 update 随机选择。

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多