创建一个不依赖于Snap实例的组

Create a group that doesnt depend on a Snap instance

本文关键字:Snap 依赖于 实例 一个 创建      更新时间:2024-05-13

以下是我想要做的:

var a = Snap("#id");
var group = new SnapGroup(); // unfortunatly didnt find how to do it
// for some reasons i dont want to do a.group();
group.circle(5,5,5);
a.add(group);

以下是我所做的:

var a = Snap("#id");
s = Snap(); // creates a SVG element instead of a group
s.circle(5,5,5);
a.add(s);

它工作,圆圈被渲染,但我不能移动组:

s.attr({"x":60}); // the group doesnt move

事实上,当我们将和<svg>元素嵌入到另一个元素中时,看起来是这样的。然后就不可能将嵌入的svg元素移动到父元素中。

我想知道如何在不执行snapInstance.group()的情况下创建组元素?然后将其添加到Snap实例中。

从您的描述中,我仍然不太确定您想要什么,因为我怀疑这可能取决于您如何生成原始组(如果它只是一个svg标记或导入)。

 Snap.parse('<g></g>'); may be enough to fiddle with, to parse into a fragment.

看看这是否有帮助。。。这是一个包含两个独立SVG元素和Snap实例的示例。它将从带有组的原始SVG标记字符串中绘制一个矩形,从Snap中添加一个圆,在第二个实例中,它还将把组平移75。

<svg id="svg1" width="200" height="200"></svg><br />
<svg id="svg2" width="200" height="200"></svg>
...
    var paper1 = Snap("#svg1");
    var paper2 = Snap("#svg2");
    var groupMarkup = '<g><rect x="0" y="0" width="70" height="70" opacity="0.3"/><text x="0" y="15">original</text></g>'; 
    var parsedMarkup1 = Snap.parse( groupMarkup ); //parse from a string derived elsewhere
    var parsedMarkup2 = Snap.parse( groupMarkup );

    // example1  just use the markup with its original group
    paper1.add( parsedMarkup1 )
          .add( paper1.circle(100,50,50)
                      .attr('fill', 'red' ) );

    // example2, will create a new group and add the existing group to it, and then move it
    var outerG = paper2.g()
                       .transform('t75,0');    //create a group and move it
    outerG.add( parsedMarkup2 );               //add the original group/square
    outerG.add( paper2.circle(70,50,50)        //add a circle
                      .attr('fill', 'blue' ) );
   var clone = outerG.clone();                  //lets create a clone
    clone.transform('r45t50,50');               //translate and rotate the clone

小提琴在这里http://jsfiddle.net/v4bJa/