Question

I am trying to use Snap SVG library to move an element in an SVG graphic around the screen. This is the code of the element:

<g id="butterfly">
  <path id="wings" fill="#FFFFFF" stroke="#CFEA90" stroke-width="4" stroke-miterlimit="10" d="M139.741,74.038c-5.847-1.477-11.794,1.029-14.605,5.736c-0.463-5.791-5.095-10.963-11.275-12.115c-7.017-1.309-13.365,3.059-14.179,9.755c-0.654,5.381,2.469,10.622,7.36,13.155c-0.143,0.146-0.28,0.284-0.403,0.402c-3.157,3.055-2.81,7.082,0.777,8.994c3.586,1.912,9.053,0.985,12.211-2.071c0.836-0.809,1.773-2.517,2.632-4.62c-0.068,2.586,0.13,4.835,0.632,6.038c1.724,4.127,6.377,7.274,10.394,7.031c4.017-0.244,5.876-3.786,4.152-7.913c-0.067-0.16-0.14-0.343-0.215-0.538c5.45-0.264,10.315-3.753,11.775-8.957C150.814,82.459,146.669,75.79,139.741,74.038z"/>
  <path id="body" fill="#97BD40" d="M123.467,99.008c-0.3,1.287-1.587,2.086-2.873,1.786l0,0c-1.287-0.3-2.086-1.587-1.786-2.873l5.159-22.099c0.3-1.287,1.587-2.086,2.873-1.786l0,0c1.287,0.3,2.086,1.587,1.786,2.873L123.467,99.008z"/>
</g>

I want to move this element around the screen (e.g., I want to move it up and then left and then down again to the initial position), so I first create a canvas and get the element. I use this code:

var canvas = Snap("div#canvas");

Snap.load("MyImage.svg", function (image) {

    var butterfly = image.select("g#butterfly");    
    canvas3.append(butterfly);

    // Now I want to move the element around...
}

Does anybody have an idea?

I've found information about moving a circle or a rectangle, which have attributes like x, y, cx or cy that are easy to modify, but in my case I don't have those attributes...

Was it helpful?

Solution

Set a transform on the butterfly. You want a translate transform to move it. E.g.

butterfly.transform("t100,100");

That syntax is the same as Raphael. But you can also use a Snap matrix

var t = new Snap.Matrix()
t.translate(100, 100);
butterfly.transform(t); 

OTHER TIPS

The SVG Transform Attribute applies a list of transformations to an element and it's children (here's a very good tutorial on that: https://www.dashingd3js.com/svg-group-element-and-d3js). You can use different types of transformations; for example, as Totty asks, to move just to x=1 and y=1, you'd use

myElement.setAttribute('transform','translate(30,100)');

More information on that in this answer: How to manipulate translate transforms on a SVG element with javascript in chrome?. Once you read more you notice you could even use animations really easily with Snap:

myElement.animate({ transform:'translate(30,100)'}, 700, mina.bounce );

maybe you can try

butterfly.drag()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top