Add animation between two objects in Fabric js

I have a very basic application that allows you to create shapes and associate them with a line. To do this, you will do the following.

Example 1. Click new animation 2. add rectangle 3. add child 4. add circle 

You can move shapes around, drag and resize. I was wondering if animation could be added between two objects. So, for example, a small round circular ball could plunge into a line between two objects. I checked the demos on the animation page in js j, but am not sure what can be done with object b.

Here is the FIDDLE .

+5
source share
1 answer

I do not know if you can use the built-in animation function in the fabric, because, as you say, these objects can move. But you can do something like this quite easily by hand using a little Math:

enter image description here

You can do this by looking at it as a wave oscillating between 0 and 1. The correct formula for this function is:

enter image description here

  • When the “angle” is 0 or a multiple of 2π, the amplitude is 0, so the ball is in the center of the object1
  • When the “angle” is a multiple of π, the amplitude is 1, and the ball is in the center of the object2
  • When the amplitude is 0.5, the ball is between two objects

You can simply increase the angle depending on the time, time and duration.

 var animateBallBetweenObjects = function (obj1, obj2) { // Add the "ball" var circle = new fabric.Circle({ radius: 10, fill: 'blue', left: obj1.getCenterPoint().x, top: obj1.getCenterPoint().y, originX: 'center', originY: 'middle', selectable: false }); canvas.add(circle); var period = 1000; var amplitude = 0; var angle = 0; var prevTime = Date.now(); var loop = function () { // Calculate the new amplitude var now = Date.now(); var elapsed = now - prevTime; prevTime = now; angle += Math.PI * (elapsed / (period * 0.5)); amplitude = 0.5 * (Math.sin(angle - (0.5 * Math.PI)) + 1); // Set the new position var obj1Center = obj1.getCenterPoint(); var obj2Center = obj2.getCenterPoint(); circle.setLeft(obj1Center.x + (amplitude * (obj2Center.x - obj1Center.x))); circle.setTop(obj1Center.y + (amplitude * (obj2Center.y - obj1Center.y))); canvas.renderAll(); requestAnimationFrame(loop); } // Animate as fast as possible requestAnimationFrame(loop); }; 

FIDDLE with him here.

+5
source

All Articles