JS Flying Animation, Accelerated Animation, Swap In and Out Effects

Online Preview /my/demo/fly.html

<!DOCTYPE html>
<body>
<div id="gift-fly" style=" position: absolute; width: 50px;height: 50px;background-color: #327dff "> Animation Box</div>
</body>
<script>
let flyDiv = document.getElementById("gift-fly")
animate(flyDiv, {"left": 500}, 3000, "easeIn").then(res => {
console.log("Flying in animation completed")
animate(flyDiv, {"left": 0}, 3000, "easeOut").then(res => {
console.log("Flying out animation completed")
})
})

/**
* @param elem {HTMLElement} The HTML element to animate
* @param params {JSON} HTML attributes to modify during the animation
* @param duration {Number} Optional, duration of the animation in milliseconds
* @param easing {String} Optional, easing mode of the animation, easing in easeIn, easing out easeOut
*/
function animate(elem, params, duration, easing) {
return new Promise(success => {
/*
* Description: tween animation algorithm.
* @param Number t: The time the animation has been running (actually how many times/frames)
* @param Number b: Starting position
* @param Number c: Ending position
* @param Number d: Time it takes from starting position to ending position (actually how many times/frames)
*/
let tween = {
easeIn: function (t, b, c, d) {// easing in
return c * (t /= d) * t + b;
},
easeOut: function (t, b, c, d) {// easing out
return -c * (t /= d) * (t - 2) + b;
}
};
let attribute = {
get: function (elem, attr) {
let val;
if (elem.currentStyle) {
if (attr === "opacity") {
val = elem.filters.alpha[attr];
} else {
val = elem.currentStyle[attr];
}
} else {
val = getComputedStyle(elem)[attr];
if (attr === "opacity") {
val = 100 * val;
}
}
return val;
},
set: function (elem, attr, val) {
if (attr == 'opacity') {
elem.style.filter = 'alpha(opacity=' + (val) + ')';
elem.style.opacity = (val) / 100;
} else {
elem.style[attr] = val + 'px';
}
}
};
let effect = {
animate: function (elem, params, duration, easing) {
let dt = new Date().getTime(),
b = 0,
c = 0,
d = duration || 500,
fps = 1000 / 60;

let changes = [];

for (let attr in params) {
b = parseFloat(attribute.get(elem, attr));
c = params[attr] - b;

changes.push({

attr: attr,

b: b,

c: c
});
}

easing = easing || "easeOut";
setTimeout(function () {
let t = new Date().getTime() - dt;
let b, c, attr;
for (let i = 0; i < changes.length; i++) {
b = changes[i].b;
c = changes[i].c;
attr = changes[i].attr;

attribute.set(elem, attr, tween[easing](t, b, c, d));
if (d <= t) {
attribute.set(elem, attr, params[attr]);
success();
return;
}
}
setTimeout(arguments.callee, fps);
}, fps);
}
};
effect.animate(elem, params, duration, easing);
})
}
</script>
</html>