4

我正在使用 RaphaelJS 开始一个绘画应用程序。跟踪在纸上(用鼠标)绘制的所有元素的最佳方法是什么?

我想到的第一种方法是将所有绘制的元素附加到一个数组中,但如果 R​​aphaelJS 有一个“开箱即用”的解决方案,这可能不会那么有效。

我检查了API,但没有找到任何我想要的东西......我运气不好?

4

3 回答 3

3

我想这取决于您说“跟踪”时的意思。

您可以使用循环给定纸张上的所有元素,Paper.forEach并且可以使用Paper.getById.

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

于 2013-08-08T16:26:13.370 回答
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 的第 3 个索引处的元素。

因此,将绘图逻辑与数据结构分开,即填充数据结构,然后将数据结构传递给某个函数,该函数将在面板上进行所有绘图。

于 2013-08-08T17:52:46.903 回答
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. 可扩展 - 模型可能包含您想要的任何值。
于 2013-08-10T11:35:44.660 回答