搬運https://www.zybuluo.com/dengzhirong/note/184284git
緩動函數, 主要用在控制動畫上, 它是一個區間函數
用它來作動畫, 實際上就是將這個函數離散化
好比在x軸上取100個點, 計算獲得f(x)值 就是獲得了這個動畫在這100步的變化過程github
緩動函數須要四個參數
b 函數開始值
c 函數結束值
d 結束時間(實際上這裏並非真正意義上的時間, 而是離散時的取樣)
t 通常爲0 也就是從開始值開始變化函數
例如我將d值設置爲100 就是講這個連續的函數離散爲100個點 根據t值(x軸位置)的不一樣獲得不一樣的結果( f(x)的值 )動畫
兩個簡單的例子code
function timeoutMove() { var pos = 0; var t1 = +new Date; var b = 50, //開始值 c = 100, //結束值 d = 100, //運算次數 雖然不少文章這裏說時間 但這不是時間 不過這個值決定了執行時間 約1677ms t = 0; function run() { //t =0時 運算結果是 b值 //t =d時 運算結果是d值 pos = Math.ceil(Tween.Quad.easeOut(t, b, c - b, d)); cube.style.top = pos + 'px'; console.log('t= ',t,'pos=',pos); t++; timer = setTimeout(run, 1000 / 60); if (t >= d) { clearTimeout(timer); console.log(+new Date - t1); } } run(); }
再來一個RAF的例子ci
function raqMove() { var move = 0, t = 0, end = 50, t1 = +new Date; function run() { move = Tween.Sine.easeInOut(t, 0, 500, end) cube.style.left = move + 'px'; console.log('t= ',t,'move=',move); t++; //由於是使用的RAF 不能精確的獲得執行結束時間 //大約執行結束時間是 50*16.7 = 835ms 確定會比這個時間長 //16.7 是根據一秒60楨來計算的 if (t <= end) { requestAnimationFrame(run) } else { console.log(+new Date - t1) } } run(); }
如何將緩動函數真正的用在動畫中呢
來看個緩動函數大集合
https://github.com/tweenjs/tween.js/blob/master/src/Tween.jsget
接下來和動畫集合一下it
util = { animate: function(ele, style, time, animate) { time = time || 432; animate = animate || 'Linear'; var t1 = +new Date; var begins = [], ends= []; for (key in style) { if(key == 'opacity'){ begins[key] = parseFloat(window.getComputedStyle(ele)[key]) console.log(begins[key]); }else{ begins[key] = parseInt(window.getComputedStyle(ele)[key]); } } var d = Math.ceil(time / (1000/60)), //計算次數 t = 0; var b = 1, c = 0.1 function run() { for (key in style) { if(key == 'opacity'){ ele.style[key] = Tween[animate](t, begins[key], style[key]- b, d); }else{ ele.style[key] = Tween[animate](t, begins[key], style[key]- begins[key], d) + 'px'; } } t++; if (t <= d) { requestAnimationFrame(run); }else{ console.log(+new Date - t1); } } run(); } }
這樣調用就能夠io
util.animate(cube, { top: 500, left:100, opacity: 0.1 }, 1000, 'easeInOut');