Search code examples
snap.svgsvg-animate

Snap.js Moving SVG Object Along a Specified Path


I am trying to animate SVG which I created with Inkscape using Snap.js. But the issue I find is that when trying to animate the object is not responding correctly.

Svg is loaded like this

var s = Snap("#svgB");
var g ;
var group = s.g();

var myPathB = s.path("M246,1723.4c-27.2-18-76.8-50.3-61.3-73.2c15.5-22.8-4.9-42.7-15.8-34.8 c-31.9,3.9-16.6-45.2-23.9-64.6c-4.5-11.9-30.3-38.4-11.6-45c21.6-20.5-20.4-25.7-4.4-28.1c16-2.4,14.3-22.7-3.3-30 c-9.5-4-30.3-69.9-7.9-74.1c22.3-4.2,6.1-65.6,8.8-86.7c3.6-27.6,19.1-63.4,34.8-51c15.7,12.5,17.6,14.2,20.7-8 c3-22.2,14.8-21.8,20.9-5.7c6.1,16.2,55.8-14.1,75.6-37.3c46.5-54.5,22.3-50.4-2-68.5c-30.9-23,20-100,20-100").attr({
  fill: "none",
  strokeWidth: "17",
  stroke: "#FFF",
  strokeMiterLimit: "10",
  strokeLinecap: "round",
  strokeDasharray: "10",
  strokeDashOffset: "1000"
});
  
 
	Snap.load("car.svg", function (f) {
			 g=  f.select("g");
			 g.drag(function () {
				      animateAlongPath(myPathB,group,0,100330);  
 
                }); 
 
                s.append(group);
                g.drag();
				
				
	});

The function I use is this

function animateAlongPath( path, element, start, dur ) {
 var len = Snap.path.getTotalLength( path );
setTimeout( function() {
        Snap.animate( 0, len, function( value ) {
        var movePoint = Snap.path.getPointAtLength(path,value);
		console.log(movePoint);
        element.transform('t' + movePoint.x + ',' + movePoint.y)	 ;		 
}, dur,mina.easeinout); 
 });
} 

Codepen: http://codepen.io/georgegijo/pen/mEdEYK


Solution

  • You may need to provide a working example, as the code above isn't quite enough to test.

    I suspect the initial problem may be with this line though...

    element.attr({ x: movePoint.x, y: movePoint.y });
    

    I note that earlier in the code, the element is called 'g'. Is this because the element is a 'group' element ?

    If so, you can't use x,y as they aren't valid attributes for a group element. You would need to use a transform. So you would change the code to look something like...

    element.transform('t' + movepoint.x + ',' + movepoint.y ) 
    

    The 't' is for translate, you can also add an 'r' later with an angle if you want to rotate it by movepoint.alpha.

    If its not a group element, and its a rect for example, then you can ignore the above though, and I would edit the question to include what actually happens, any errors etc, plus possibly include the object being moved etc so we can do a test.

    If its an 'svg' element itself created by inkscape, you may want to append it to a 'group' element if not done already, and follow the above, as 'svg' elements don't really support a transform (so maybe the x,y could work).