上一篇我們完成了單一方塊的往返動畫,但程式碼寫死在一個函式裡,不易擴充。本篇我們把方塊抽象成一個物件(Box),透過建構函式與原型方法來組織程式碼,並一次驅動多個不同顏色、速度與大小的方塊同時運動。
關鍵改進在於:每個方塊各自維護自己的座標、速度與更新節奏(透過 delay 控制幀率),再由主迴圈統一呼叫各自的 update 方法。這樣一來,新增方塊只需要多建立一個物件即可,維護起來清爽許多。
<canvas id="canvas2" width="250" height="300" style="background-color:black">
你的瀏覽器不支援 Canvas 標籤,請使用 Chrome 瀏覽器或者 Firefox 瀏覽器
</canvas><br/>
<input type="button" value="開始" onclick="move_box2()"/>
<input type="button" value="暫停" onclick="stop()"/>
<script type="text/Javascript">
//定時器
var interval=null;
//停止動畫
function stop(){
clearInterval(interval);
}
//===================================================================
//重新組織代碼
//====================================================================
//方塊的構造函數
function Box(color,x,y,w,h,delta){
this.color=color;
this.x=x;
this.y=y;
this.w=w;
this.h=h;
this.delta=delta;
//三十幀
this.fps=30;
//每一幀的延遲時間
this.delay=1000/this.fps;
//上一次重繪的時間
this.last_update=0;
}
//方塊更新
Box.prototype.update=function(canvas){
//獲取當前時間
var now=(new Date()).getTime();
//如果達到了延遲時間,則更新數據
if((now-this.last_update)>this.delay){
//改變 y 坐標
this.y=this.y+this.delta;
//上邊緣檢測
if(this.y<0){
this.y=0;
this.delta=-this.delta;
}
//下邊緣檢測
if((this.y+this.h)>canvas.getAttribute("height")){
this.y=canvas.getAttribute("height")-this.h;
this.delta=-this.delta;
}
//記下最新一次繪制時間
this.last_update=now;
}
}
function move_box2(){
//停止動畫
stop();
//畫布對象
var canvas=document.getElementById("canvas2")
//獲取上下文對象
var ctx = canvas.getContext("2d");
//清空畫布
ctx.clearRect(0,0,canvas.getAttribute("width"),canvas.getAttribute("height"));
//創建多個方塊對象
var boxes=[];
boxes[0]= new Box("red",3,2,10,35,2,10);//速度10
boxes[1]= new Box("blue",60,28,44,15,5);//速度20
boxes[2]= new Box("green",130,200,23,18,10);//速度30
boxes[3]= new Box("pink",200,150,35,10,20);//速度40
//開始動畫繪制
interval = setInterval(function(){
for(var i=0;i<boxes.length;i++){
//取出一個方塊
var box=boxes[i];
//清空這個方塊
ctx.clearRect(box.x,box.y,box.w,box.h);
//更新數據
box.update(canvas);
//保存狀態
ctx.save();
//設置顏色
ctx.fillStyle=box.color;
//移動坐標
ctx.translate(box.x,box.y);
//重新繪制
ctx.fillRect(0,0,box.w,box.h);
//恢復狀態
ctx.restore();
}
},1);//盡可能快的循環
}
</script>
源碼下載:donghua2.rar