纯JavaScript动画缓和

aki*_*uri 5 javascript animation easing

我一直试图找到一个纯粹的JavaScript轻松实现几个小时,但找不到任何.接近的那些没有任何意义.我所能找到的只是一堆没有实现的缓动函数.

例如,这些函数:

function linear(time, begin, change, duration) {
    return change * time / duration + begin;
}

function easeInQuad(t) {
    return t*t
},

function easeOutQuad(t) {
    return t*(2-t)
},
Run Code Online (Sandbox Code Playgroud)

困扰我的一件事是fps在哪里发挥作用?它与持续时间直接相关.我没见过它.

如何在以下动画中实现上述缓动功能?

的jsfiddle

var box = document.getElementById("box");

var fps		= 60;
var duration	= 2; // seconds
var start	= 0; // pixel
var finish	= window.innerWidth - box.clientWidth;
var distance	= finish - start;
var increment	= distance / (duration * fps);

var position = start;

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

var handler = setInterval(move, 1000 / fps);
Run Code Online (Sandbox Code Playgroud)
body {
  background: gainsboro;
}
#box {
  width: 100px;
  height: 100px;
  background: white;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  position: absolute;
  left: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div id="box"></div>
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 10

你可以使用一个time变量并为每一帧增加它,并使用你已经拥有的值的正确位置的缓动函数.

// 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);
Run Code Online (Sandbox Code Playgroud)
body {
  background: gainsboro;
}
#box {
  width: 100px;
  height: 100px;
  background: white;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  position: absolute;
  left: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div id="box"></div>
Run Code Online (Sandbox Code Playgroud)

  • 我已经在[什么是缓动函数?](http://stackoverflow .com/questions/8316882/what-is-an-easing-function/38513962#38513962)有关实施的信息。既然你在这个问题上帮助了我,我想你可能想知道:) (2认同)