除了傳統的逐格圖片,我們也能以 JavaScript 動態移動大量小方塊,讓它們組合出動畫效果。本文分享一個以指令序列驅動方塊移動、顯示與隱藏的動畫引擎。
程式碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<style>
.ld_anipic{ position:absolute; width:8px; height:8px; background-color:#ccc;}
</style>
<script>
//ld動畫組建
//被加載的divID
function ldAni(contain_id,id_flag,start_id){
this.contain_id=contain_id;
this.id_flag=id_flag;
this.start_id=start_id;
this.a = new Array();
this.tempa=new Array();
this.Add_cmd=function(cmd){
this.a.unshift(cmd);
};
this.bakdata=function(){
this.tempa = this.a.concat();
};
this.steprun=function(){
if (this.a.length < 1) {
//從副本恢復數組到緩存,用於循環顯示
//this.a = this.tempa.concat();
return;
}
var x = this.a.pop();
var cmds = x.toString().split(";"); //字符分
for (var i = 0; i < cmds.length; i++) {
if(cmds[i].toString().length>0){
var d = cmds[i].toString().split(",");
this.dit(d[0], d[1], d[2], d[3]);
}
}
};
this.dit=function(objid, cmd, cs1, cs2){
var obj = null;
try{
obj = document.getElementById(this.id_flag + objid);
}catch(e){}
//move 移動的意思
if (cmd == "m") {
obj.style.left = cs1 + "px";
obj.style.top = cs2 + "px";
}
//show 顯示的意思
else if (cmd == "s") {
obj.style.display = "block";
}
//hidden 隱藏的意思
else if (cmd == "h") {
obj.style.display = "none";
}
else if(cmd=="a"){
this.start_id++;
var atag = document.createElement("a");
atag.setAttribute("class", "ld_anipic");
atag.setAttribute("id",this.id_flag + this.start_id);
document.getElementById(this.contain_id).appendChild(atag);
try{
obj = document.getElementById(this.id_flag + this.start_id);
}catch(e){}
obj.style.display = "block";
obj.style.left = cs1 + "px";
obj.style.top = cs2 + "px";
}
}
}
//動畫速度可以在這裡控制
var ani=new ldAni("ld_anicon","ldanim_pic",1);
ani.Add_cmd("1,a,0,0");
ani.Add_cmd("1,a,10,0");
ani.Add_cmd("1,a,20,0");
// ... 其餘指令省略,依序描述每個方塊的座標與動作
ani.bakdata();
setInterval("ani.steprun()",50);
</script>
</head>
<body>
<div>用js來進行一些圖片的移動來組成動畫效果</div>
<table>
<tr>
<td id="ld_anicon" style=" position:relative; display:inline-block; width:160px;">
</td>
<td style="display:inline-block; font-size:250px;">
SOFT.com
</td>
</tr>
</table>
</body>
</html>這個引擎的核心是 ldAni 建構函式,它透過 Add_cmd 收集指令序列,再由 steprun 逐條解析並呼叫 dit 執行移動(m)、顯示(s)、隱藏(h)或新增方塊(a)等動作。透過 setInterval 控制 steprun 的呼叫頻率,即可調整動畫播放速度。