Snap SVG - moving a loaded item around

I am trying to use the Snap SVG library to move an element in SVG graphics across the screen. This is the item code:

<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 (for example, I want to move it and then leave and then return to its original position), so I first create a canvas and get the element. I am using 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 anyone have any ideas?

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

+6
source share
2 answers

Set the transform to a butterfly. You want to convert a translation to move it. For instance.

 butterfly.transform("t100,100"); 

The syntax is the same as that of Raphael. But you can also use Snap matrix

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

The SVG Transform attribute applies a list of transformations to an element and its children (here is a very good tutorial on this subject: https://www.dashingd3js.com/svg-group-element-and-d3js ). You can use various types of conversions; for example, as Totti says, move only to x = 1 and y = 1, you should use

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

More information on this in this answer: How to manipulate translational transformations on an SVG element with javascript in chrome? . After you read more, you'll notice that with Snap you can easily use animations:

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

All Articles