Pure JavaScript animation easing

℡╲_俬逩灬. 提交于 2019-11-27 23:19:15
Nina Scholz

You could use a time variable and increment it for every frame and use the easing functions for the right position with the values you already have.

// formula     http://easings.net/
// description https://stackoverflow.com/questions/8316882/what-is-an-easing-function
// x: percent
// t: current time,
// b: beginning value,
// c: change in value,
// d: duration
function easeInOutQuad(x, t, b, c, d) {
    if ((t /= d / 2) < 1) {
        return c / 2 * t * t + b;
    } else {
        return -c / 2 * ((--t) * (t - 2) - 1) + b;
    }
}

function move() {
    //position += increment;
    time += 1 / fps;
    position = easeInOutQuad(time * 100 / duration, time, start, finish, duration);

    if (position >= finish) {
        clearInterval(handler);
        box.style.left = finish + "px";
        return;
    }
    box.style.left = position + "px";
}

var box = document.getElementById("box"),
    fps = 60,
    duration = 2, // seconds
    start = 0, // pixel
    finish = window.innerWidth - box.clientWidth,
    distance = finish - start,
    increment = distance / (duration * fps),
    position = start,
    time = 0,
    handler = setInterval(move, 1000 / fps);
body {
  background: gainsboro;
}
#box {
  width: 100px;
  height: 100px;
  background: white;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  position: absolute;
  left: 0;
}
<div id="box"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!