Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric JS : How to animate the top and left position of a triangle simultaneously? + animate bug

My question seems relatively easy, but after a couple of hours googling I don't get any more info about that.

Basically I would like to use the animate function to move the center of two triangles (or one to start with) around another triangle. I guess it should represents an animation in three steps but I can't get something working.

Note that it's the first time I use it, I'm afraid it may sound obvious for some of you.

Also I am not sure I have set up things properly (based on example and only animating one property) as the animation doesn't want to fire up :/

function createTriangle() {
  var canvas2 = new fabric.Canvas('myCanvas');

  var triangle = new fabric.Triangle({
    width: 300, height: 300, fill: 'red', left: 30, top: 0
  });

  triangle.animate('top', '200', {
    duration: 1000,
    onChange: canvas2.renderAll.bind(canvas2),
    onComplete: function() {
      //callback code goes here
    }
  });

  canvas2.add(triangle);
}

Anyone has an idea why it is not working?

Thanks

like image 583
daneczech Avatar asked Dec 25 '22 08:12

daneczech


2 Answers

Ease example:

  triangle.animate({left: 100, top: 100 }, {
      duration: 1000,
      onChange: canvas.renderAll.bind(canvas),
   });
like image 176
dmitri Avatar answered May 16 '23 06:05

dmitri


I'm not a Fabric user, so maybe there's a better way, but the call to .animate() is non-blocking, so you can just request animations for two properties in a row:

triangle.animate('top', '+=100', {
  duration: 1000,
  onChange: canvas.renderAll.bind(canvas),
});

triangle.animate('left', '+=100', {
  duration: 1000,
  onChange: canvas.renderAll.bind(canvas),
});

Here is the demo on jsbin. I read on the Fabric docs that this way of using onChange can lead to poor perfomance. If that's your case, you can use requestAnimationFrame, or code your own loop

like image 37
Raffaele Avatar answered May 16 '23 08:05

Raffaele