0

I want to animate a curved motion (no rotation) of an object by using svg.js. But I can't find any easy solution for this problem. I wrote two little functions which work fine, but it isn't working like a normal animation, and it doesn't run perfectly in the background.

I would prefer some solution like this:

var draw = SVG("drawing").size(500,500);
var rect = draw.rect(50,50);
rect.animate().curvedmove(100,100);

The two functions I made:

function animateJump(object,start,end,ampl,y,i=0){
    var speed = 25;
    var pos = 0;
    pos = start+i*((end-start)/speed);
    object.animate(1).move(pos,y+bounceFunction(start,end,ampl,pos));

    if (i <= speed){
        animateJump(object,start,end,ampl,y,i+1)
    }
}


function bounceFunction(a,b,c,x){
    return -1 * (x-a)*(x-b) * c * (4/((a-b)*(b-a)));
}

Is there some easy solution?

Thanks for any help!

qube13
  • 85
  • 2
  • 11

1 Answers1

0

The animate method establish a new animation context in which runs the timer you specified (1 sec by default). So if you do el.animate().move(100,100) the element will move to position 100,100 in 1 second. However, if you want to use your own function you need to listen to the during event which gives you the current position from 0-1 in time.

el.animate().during(function(pos, morphFn, easedPos) {
  this.move(pos, bounceFunction(pos))
})

Note that pos is a value between 0 and 1 so setting it directly as coordinate does not make that much sense. You need to figure our the start and end value of the move and calculate it yourself (or use the morphFn like morphFn(start, end))

Example:

var startX = 100
var endX = 300

var startY = 100
var endY = 300

el.animate().during(function(pos, morphFn, easedPos) {
  var x = morphFn(startX, endX)
  var y = SVG.morph(bounceFunction(pos))(startY, endY)

  this.move(x, y)
})

the morphFn is by default bound to the current position. So if you have your own position (like when using your custom bounce function) you need to create a new morph function which you can do with the SVG.morph method. This method expects a position and gives back a morph function bound to this positon.

So this would be the same:

  var x = SVG.Morph(pos)(startX, endX)
  var y = SVG.Morph(bounceFunction(pos))(startY, endY)
Fuzzyma
  • 7,619
  • 6
  • 28
  • 60