Add animation between two objects in Fabric js

℡╲_俬逩灬. 提交于 2019-12-05 10:20:36

I don't know if you can use the built in animation function in fabric because as you say these objects might be moving around themselves. But you can make something like this quite easily manually using a bit of Math:

You could do this by treating it like a wave oscillating between 0 and 1. The correct formula for this function is:

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

You can just increase the angle based on the time, on whatever period, or duration you want.

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 it here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!