用慣 jQuery 的人,大概都欣賞過它的動畫引擎。它並不是專門為動畫而生,模擬真實世界的物理感也有限,但在網頁這個場域裡已經遊刃有餘。動畫長期是 Flash 的專屬地盤,只是 Flash 飽受安全漏洞、需要外掛、檔案龐大與效能消耗之苦,HTML5 興起後連 Adobe 自己都轉移陣地了——不過很長一段時間內,Flash 仍不會被完全放棄。
用過 Flash 的人都知道時間軸上佈滿了「幀」。每一幀其實就是一個鏡頭,鏡頭連續播放就成了動畫,原理和電影完全相同。人眼分辨畫面連貫與否有時間門檻,大約每秒 30 幀就不容易看到閃爍,電影則是 24 幀。所以只要能把切換頻率穩定在每秒 30 次上下,視覺上就會流暢——具體還是要看執行環境,這部分本文也只算入門理解,有興趣可以再深入。
首先決定幀頻(每秒多少幀)。有了總時長,就能算出整段動畫有多少「畫面」,也就是總幀數。這種設計有個明顯缺陷:總時長不一定剛好是整數幀(除非 1ms 一幀),所以引擎必然存在誤差。有了總幀數之後,播放到最後一幀動畫就結束;若要重複播放,把當前幀歸零即可。
這樣設計有個很大的好處:可以直接跳到指定幀,等同 Flash 的 gotoAndStop 與 gotoAndPlay。整個引擎的 API 幾乎都是照 Flash 的模型設計,包含核心的 enterFrame——位置就是依「進入第幾幀」來計算的,另外還有 stop、play、next 等。因為目前這個版本寫得相當簡單粗糙,先不逐一細談。
var animation = function(obj) {
this.obj = obj;
this.frames = 0;
this.timmer = undefined;
this.running = false;
this.ms = [];
}
animation.prototype = {
fps: 36,
init: function(props, duration, tween) {
this.curframe = 0;
this.initstate = {};
this.props = props;
this.duration = duration || 1000;
this.tween = tween || function(t, b, c, d) {
return t * c / d + b;
};
this.frames = Math.ceil(this.duration * this.fps / 1000);
for (var prop in this.props) {
this.initstate[prop] = {
from: parseFloat($util.dom.getStyle(this.obj, prop)),
to: parseFloat(this.props[prop])
};
}
},
start: function() {
if (!this.running && this.hasNext()) {
this.ms.shift().call(this)
}
return this;
},
// 開始播放
play: function(callback) {
var that = this;
this.running = true;
if (this.timmer) {
this.stop();
}
this.timmer = setInterval(function() {
if (that.complete()) {
that.stop();
that.running = false;
if (callback) {
callback.call(that);
}
return;
}
that.curframe++;
that.enterFrame.call(that);
}, 1000 / this.fps);
return this;
},
// 停止動畫
stop: function() {
if (this.timmer) {
clearInterval(this.timmer);
this.timmer = undefined; // 清除掉 timmer id
}
},
go: function(props, duration, tween) {
var that = this;
this.ms.push(function() {
that.init.call(that, props, duration, tween);
that.play.call(that, that.start);
});
return this;
},
// 向後一幀
next: function() {
this.stop();
this.curframe++;
this.curframe = this.curframe > this.frames ? this.frames : this.curframe;
this.enterFrame.call(this);
},
// 向前一幀
prev: function() {
this.stop();
this.curframe--;
this.curframe = this.curframe < 0 ? 0 : this.curframe;
this.enterFrame.call(this);
},
// 跳躍到指定幀並播放
gotoAndPlay: function(frame) {
this.stop();
this.curframe = frame;
this.play.call(this);
},
// 跳到指定幀停止播放
gotoAndStop: function(frame) {
this.stop();
this.curframe = frame;
this.enterFrame.call(this);
},
// 進入幀動作
enterFrame: function() {
var ds;
for (var prop in this.initstate) {
ds = this.tween(this.curframe,
this.initstate[prop]['from'],
this.initstate[prop]['to'] - this.initstate[prop]['from'],
this.frames).toFixed(2);
$util.dom.setStyle(this.obj, prop, ds)
}
},
// 動畫結束
complete: function() {
return this.curframe >= this.frames;
},
hasNext: function() {
return this.ms.length > 0;
}
}
整個引擎靈魂在 enterFrame:每一幀都呼叫緩動函式 tween(當前幀, 起始值, 變化量, 總幀數),算出這一幀該顯示的位置,再寫進 style。go() 把動畫排進佇列、start() 取出執行,於是串接多段動畫變成很自然的事。
這支工具檔負責型別檢測、深拷貝、DOM 樣式讀寫、事件綁定、AJAX 與客戶端環境判斷,其中最關鍵的是 dom.getStyle/setStyle(動畫靠它們讀起始值與寫入中間值)以及 client(用 userAgent 判斷 IE/Firefox/WebKit 等引擎與 Windows、iOS、Android 等平台)。緩動部分收錄了 Tween 家族的一整套公式:
它們的簽名都是 f(t, b, c, d):t 是當前時間/幀、b 是起始值、c 是變化量、d 是總時長。例如:
Linear: function(t, b, c, d) {
return c * t / d + b;
},
Quad: {
easeIn: function(t, b, c, d) {
return c * (t /= d) * t + b;
},
easeOut: function(t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
},
easeInOut: function(t, b, c, d) {
if ((t /= d / 2) < 1) return c / 2 * t * t + b;
return -c / 2 * ((--t) * (t - 2) - 1) + b;
}
}
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>無標題文檔</title>
<script src="util.js" type="text/javascript"></script>
<script src="animate.js" type="text/javascript"></script>
<style type="text/css">
body{behavior:url("csshover.htc")}
*{padding:0;margin:0}
.mianbox{width:480px;margin:50px auto;height:240px;}
.leftbtn{width:20px;background:#eee;border:1px solid #ddd;float:left;margin-right:8px;height:240px;}
.leftbtn:hover{background:#fff}
.rightbtn{width:20px;background:#eee;border:1px solid #ddd;float:right;height:240px;}
.rightbtn:hover{background:#fff}
.con{width:420px;float:left;height:240px;overflow:hidden;position:relative}
.con ul{white-space:nowrap;font-size:0;position:absolute;left:0;top:0;}
.con li{display:inline;vertical-align:bottom;margin-right:10px}
</style>
</head>
<body>
<div class="mianbox">
<div class="leftbtn" id="leftbtn"></div>
<div class="con">
<ul>
<li><img src="https://pic25.nipic.com/20121121/2969675_091845785000_2.jpg" width="205" height="240" /></li>
<li><img src="https://pic23.nipic.com/20120818/9715349_114354586392_2.jpg" width="205" height="240" /></li>
<li><img src="https://pic20.nipic.com/20120329/9715349_154806479182_2.jpg" width="205" height="240" /></li>
<li><img src="https://pic20.nipic.com/20120329/9715349_162301568121_2.jpg" width="205" height="240" /></li>
<li><img src="https://pic23.nipic.com/20120824/9715349_160522342186_2.jpg" width="205" height="240" /></li>
<li><img src="https://pic23.nipic.com/20120824/9715349_160651385195_2.jpg" width="205" height="240" /></li>
<li><img src="https://pic20.nipic.com/20120329/9715349_163520278182_2.jpg" width="205" height="240" /></li>
<li><img src="https://pic23.nipic.com/20120827/9715349_110350505124_2.jpg" width="205" height="240" /></li>
</ul>
</div>
<div class="rightbtn" id="rightbtn"></div>
</div>
<script>
/**
* @para obj 內容對象
* @para lbtn 左按鈕
* @para rbtn 右按鈕
* @para w 每次滾動的寬
* @para autotime 自動播放間隔
* @para duration 每次運行時間
* @para tween 緩動類型
*/
function scOnce(obj, lbtn, rbtn, w, autotime, duration, tween){
var am = new animation(obj),
step = 0,
ulen = obj.scrollWidth,
timmer,
dr = 'left',
that = this;
// 最右端?
function isr(){
return parseInt($util.dom.getStyle(obj, 'left')) >= 0;
}
// 最左端?
function isl(){
return ulen - Math.abs(parseInt($util.dom.getStyle(obj, 'left'))) - 10 <= w;
}
if(isr() && isl())
return;
// 左移
this.goleft = function (){
step += -1 * w;
am.go({left: step + "px"}, duration, tween).start();
}
// 右移
this.goright = function (){
step += w;
am.go({left: step + "px"}, duration, tween).start();
}
// 注冊左右按鈕事件
$util.evt.addEvent(lbtn, 'click', function(){
isl() ? that.goright() : that.goleft();
})
$util.evt.addEvent(rbtn, 'click', function(){
isr() ? that.goleft() : that.goright();
})
// 滑入暫停自動播放
$util.evt.addEvent(rbtn, 'mouseover', function(){ clearTimeout(timmer); })
$util.evt.addEvent(lbtn, 'mouseover', function(){ clearTimeout(timmer); })
$util.evt.addEvent(rbtn, 'mouseout', function(){ timmer = setInterval(auto, autotime); })
$util.evt.addEvent(lbtn, 'mouseout', function(){ timmer = setInterval(auto, autotime); })
function auto(){
if(isl()){ dr = "right"; }
if(isr()){ dr = "left"; }
that['go' + dr]();
}
timmer = setInterval(auto, autotime);
}
var _ul = document.getElementsByTagName('ul')[0],
lbtn = document.getElementById('leftbtn'),
rbtn = document.getElementById('rightbtn');
var startgo = new scOnce(_ul, lbtn, rbtn, 430, 3000, 500, $util.tween.Quint.easeInOut);
</script>
</body>
</html>
這裡刻意選了 Quint.easeInOut:起步與收尾都慢、中段快,用在輪播上比等速自然。想換風格只要替換最後一個參數,例如 Elastic.easeOut 會有彈簧感、Linear 則是機械式等速。
回頭看,這個引擎的價值不在效能,而在觀念:把動畫拆成離散的幀、用時間軸推進、把緩動抽成可替換的函式。今天 production 環境當然會用 CSS transition/animation 或 Web Animations API,把逐幀改 style 的工作交給合成器執行緒,順順得多;但理解「幀 → 緩動 → 渲染」這條鏈路,對調效能、寫自訂動畫還是非常有幫助。