RaphaelJS - 获取所有元素

4
我将开始使用RaphaelJS制作一个绘画应用程序。跟踪在画布上用鼠标绘制的所有元素,最好的方法是什么?
我最初想到的方法是将所有绘制的元素附加到一个数组中,但是如果RaphaelJS有一个“开箱即用”的解决方案,这可能不是很有效。
我查看了API,但没有找到类似于我要寻找的内容...我运气不太好吗?
3个回答

3

我猜你说的“跟踪”是什么意思。

使用Paper.forEach可以循环遍历给定纸张上的所有元素,使用Paper.getById可以提取出特定的元素。

如果使用Paper.path绘制元素,请设置一个可以存储在单独数据结构中的ID,可以使用这个SO线程中描述的方法进行设置。


1

我在Raphael.js上工作过一段时间,发现最有效的方法是将绘图逻辑与数据结构分离。我无法在此处完全编写代码(太长了),但可以通过一些代码片段给您一些想法,这可能会有所帮助。

// Create Data Structure to keep seperate track of Elements and its attribute (assuming a Drawing Panel and only Line Type here)

    function DrawingPanelStructure(Type, Attributes){
     this.Type = Type;
     this.Attributes = Attributes;
    }

    function PanelLineAttribute(Color,CurveDataX, CurveDataY)
    {
    this.Color = Color; 
    this.CurveDataX = CurveDataX;   
    this.CurveDataY = CurveDataY;
    }

// Make Global Variables

    _drawingPanelStructure = new Object();
    var ElementDrawnNumber = 0; // Keeping Track of Number of elements drawn

// Then when Drawing the element, populate the Data Structure inside a function as

     _drawingPanelStructure[ElementDrawnNumber] = new DrawingPanelStructure("Line",new PanelLineAttribute("Red",[1,5,6,7,5], [5,1,8,6,8]));
    ElementDrawnNumber = ElementDrawnNumber + 1;

// Then you can call a function to draw the Element at specific index as    
    var XData = [];
    var YData =[];
    XData.push(_drawingPanelStructure[index].Attributes.CurveDataX);
    YData.push(_drawingPanelStructure[index].Attributes.CurveDataY);

     var LineChart = Paper.linechart(0, 0, DrawinPanelWidth, DrawingPanelHeight, 0),
           XData, YData, {}
             );

    // Since in this example there is only 1 line drawn on LineChart I'll use LineChart.lines[0]
     LineChart.lines[0].attr({ "stroke": _drawingPanelStructure[index].Attributes.Color});

在绘制元素的同时为其指定唯一的 ID,这也是有帮助的。

ElementDrawn.id = "Element_" + ElementDrawnNumber;

那样你就可以确定Element_3是指_drawingPanelStructure中第三个索引处的元素。
因此,将绘图逻辑与数据结构分离,即填充数据结构,然后将数据结构传递给某个函数,该函数将在面板上执行所有绘图操作。

谢谢你的回答,我想Raphael并没有我需要的东西,所以实现一个单独的数据结构是最好的方法。幸运的是,Andre的答案对我的情况已经足够了,但你的解决方案看起来是跟踪Raphael元素的好方法!再次感谢! - projeqht

1

从我的经验来看,最好的方法是创建一个专门的对象(我们称之为DataManager),它将在数组中保存每个绘图的模型(而不是实际的Rapahel对象)。

这里是管理器存根:

function DataManager (){
    var self = this;
    self.DrawingsArray = [];
}

这里是模型桩:

function DrawingModel (name,raphael){
    var self = this;
    self.ID = someObject.generateSomeID();
    self.Name = name;
    self.Rapahel = raphael;
}

有了这个想法,我们可以创建模型,在将绘图添加到工作区后,将raphael对象的引用添加到模型中,给它一些名称或id,然后将其添加到DataManager的DrawingArray中。关于id,您还可以将其作为Raphael对象的新属性添加,以便在事件处理程序中轻松访问模型等。

主要优点包括:

  1. 易于访问任何元素。
  2. 方便保存应用程序的状态——只需保存和加载模型即可。
  3. 可扩展——模型可以存储任何您想要的值。

谢谢你的回答,最终我在我的应用程序中使用了安德烈的答案,所以我没有机会尝试这个,但它看起来和听起来都不错! - projeqht

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接