這個範例畫面上有一群半透明的小球各自以不同速度、方向四處彈跳,撞到邊界就反彈。它示範的不只是 Canvas 繪圖,還包括如何把動畫狀態整理成一個結構清楚的物件,以及暫停、繼續、增加物件這類控制如何實作。
請使用支援 HTML5 的瀏覽器開啟。
<h1>HTML5 特效 隨機彈跳的小球</h1>
<div>
<button id="stop-keleyi-com">暫停</button>
<button id="run-keleyi-com">繼續</button>
<button id="addBall-keleyi-com">增加小球</button>
<button onclick="javascript:window.location.reload();">刷新</button>
<br />每次刷新頁面的小球大小、顏色、運動路線都是新的。
</div>
<canvas id="canvas-keleyi-com"></canvas>
<style>
canvas {
display: block;
margin-left: auto; margin-right: auto;
border: 1px solid #DDD;
background: -webkit-linear-gradient(top, #222, #111);
}
</style>
程式的骨幹是一個名為 nimo 的物件,分成三個區塊:data 存設定、balls 存所有小球、fn 存方法。這種分法讓「設定」「狀態」「行為」涇渭分明。
var nimo = {
aniamted: null, // 計時器 handle,用於暫停
content: null, // 2d context
data: {
radiusRange: [5, 20], // 半徑範圍
speedRange: [-5, 5], // 速度範圍
scrollHeight: null,
scrollWdith: null
},
balls: [], // 所有小球
ele: { canvas: null },
fn: { /* 方法在下方 */ }
};
fn: {
creatRandom: function (startInt, endInt) {
return startInt + Math.floor(Math.random() * (endInt - startInt + 1));
},
init: function () {
nimo.data.scrollWdith = document.body.scrollWidth;
nimo.data.scrollHeight = document.body.scrollHeight;
nimo.ele.canvas = document.getElementById('canvas-keleyi-com');
nimo.content = nimo.ele.canvas.getContext('2d');
nimo.ele.canvas.width = nimo.data.scrollWdith - 50;
nimo.ele.canvas.height = nimo.data.scrollHeight - 100;
},
addBall: function () {
var aRandomColor = [];
aRandomColor.push(nimo.fn.creatRandom(0, 255));
aRandomColor.push(nimo.fn.creatRandom(0, 255));
aRandomColor.push(nimo.fn.creatRandom(0, 255));
var iRandomRadius = nimo.fn.creatRandom(5, 20);
var oTempBall = {
coordsX: nimo.fn.creatRandom(iRandomRadius, nimo.ele.canvas.width - iRandomRadius),
coordsY: nimo.fn.creatRandom(iRandomRadius, nimo.ele.canvas.height - iRandomRadius),
radius: iRandomRadius,
bgColor: 'rgba(' + aRandomColor.join(',') + ',0.5)'
};
oTempBall.speedX = nimo.fn.creatRandom(-5, 5) || 1;
oTempBall.speedY = nimo.fn.creatRandom(-5, 5) || 1;
nimo.balls.push(oTempBall);
},
// ...
}
有兩個細節做得很好。第一,初始座標的隨機範圍是 [半徑, 寬度 - 半徑] 而不是 [0, 寬度],這樣小球一開始就不會有半個卡在邊界外。第二,用 || 1 把抽到 0 的速度替換掉,避免出現完全不動的小球——原作者分成兩個 if 判斷,效果相同但更囉嗦。
drawBall: function (bStatic) {
nimo.content.clearRect(0, 0, nimo.ele.canvas.width, nimo.ele.canvas.height);
for (var i = 0, iSize = nimo.balls.length; i < iSize; i++) {
var oTarger = nimo.balls[i];
nimo.content.beginPath();
nimo.content.arc(oTarger.coordsX, oTarger.coordsY, oTarger.radius, 0, 10);
nimo.content.fillStyle = oTarger.bgColor;
nimo.content.fill();
if (bStatic) continue; // 靜態模式只畫不跑
// 四個邊界各自檢查,撞牆就取絕對值反向
if (oTarger.coordsX + oTarger.radius >= nimo.ele.canvas.width) oTarger.speedX = -Math.abs(oTarger.speedX);
if (oTarger.coordsX - oTarger.radius <= 0) oTarger.speedX = Math.abs(oTarger.speedX);
if (oTarger.coordsY - oTarger.radius <= 0) oTarger.speedY = Math.abs(oTarger.speedY);
if (oTarger.coordsY + oTarger.radius >= nimo.ele.canvas.height)oTarger.speedY = -Math.abs(oTarger.speedY);
oTarger.coordsX += oTarger.speedX;
oTarger.coordsY += oTarger.speedY;
}
}
反彈的數學很樸素:判斷是否越界,若越界就用 Math.abs() 加上正負號把速度方向翻轉。用 -Math.abs(x) 而非單純 -x 是為了保險——若小球因為某些原因已經跑到界外,-x 可能仍然是往外走,用絕對值強制指定方向更穩健。
run: function () {
nimo.fn.drawBall();
nimo.aniamted = setTimeout(function () {
nimo.fn.drawBall();
nimo.aniamted = setTimeout(arguments.callee, 10);
}, 10);
},
stop: function () { clearTimeout(nimo.aniamted); }
暫停與繼續就是 clearTimeout 與重新 run(),而 handle 存在 nimo.aniamted 上——這正是為什麼它要放在物件頂層而非函式內的區域變數。
這裡有兩點可以改進。第一,arguments.callee 在嚴格模式下是被禁止的,改用具名函式會更好。第二,遞迴 setTimeout 請改成 requestAnimationFrame:瀏覽器會自動對齊刷新率,分頁在背景時也會暫停,對效能與電池都友善得多。
目前的實作沒有處理「小球之間的碰撞」,它們會互相穿透。若要加上,需要兩兩比對距離是否小於半徑之和,再交換速度分量——這已進入基本物理模擬的範疇,小球數量多時還需導入空間分割來降低計算量。
另外那個 nimo 物件寫法值得學:把設定集中、狀態集中、方法集中,比散落的全域變數好維護太多。日後若要重構,把它包成 init(options) 的建構函式,就能同時產生多個互不干擾的實例。