用 Canvas 做一個會撞牆反彈的小球,是最能說明「逐幀重繪」思維的入門範例。整個效果的核心其實只有三件事:擦掉上一幀、更新座標、把球畫到新位置。
初學時最常犯的錯誤,是拿球心座標直接和方框邊界比較,結果球要有一半跑出牆外才反彈。正確做法是先算出球心可以活動的四條「內界限」:右界等於方框 x 加寬度再減半徑,左界等於方框 x 加半徑,下界與上界同理。這樣球的外緣永遠貼著牆,視覺上才自然。
反彈的本質就是把速度取負號:撞到左右牆只翻轉水平速度 ballvx,撞到上下牆只翻轉垂直速度 ballvy。同時務必把座標夾回邊界上,否則下一幀又會被判定為碰撞,畫面上就會出現抖動。
<!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>
</head>
<body>
<script type="text/javascript">
window.onload = function () {
var boxx = 20, boxy = 20, boxwidth = 350, boxheight = 250, ballrad = 10,
boxboundx = boxx + boxwidth - ballrad, // 右界
boxboundy = boxy + boxheight - ballrad, // 下界
inboxboundx = boxx + ballrad, // 左界
inboxboundy = boxy + ballrad, // 上界
ballx = 50, bally = 60, ctx, ballvx = 4, ballvy = 8;
function init() {
ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "rgb(200,0,50)";
moveball();
setInterval(moveball, 50);
}
function moveball() {
ctx.clearRect(boxx, boxy, boxwidth, boxheight); // 擦掉上一幀
moveandcheck();
ctx.beginPath();
ctx.arc(ballx, bally, ballrad, 0, Math.PI * 2, true); // 畫圓
ctx.fill();
ctx.strokeRect(boxx, boxy, boxwidth, boxheight); // 畫邊界
}
function moveandcheck() {
var nballx = ballx + ballvx, nbally = bally + ballvy;
if (nballx > boxboundx) { ballvx = -ballvx; nballx = boxboundx; }
if (nballx < inboxboundx) { nballx = inboxboundx; ballvx = -ballvx; }
if (nbally > boxboundy) { nbally = boxboundy; ballvy = -ballvy; }
if (nbally < inboxboundy) { nbally = inboxboundy; ballvy = -ballvy; }
ballx = nballx; bally = nbally;
}
init();
};
</script>
<canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>
用 setInterval 驅動動畫在今天已經不算理想,建議改用 requestAnimationFrame,讓瀏覽器依螢幕刷新率安排繪製,畫面更順也更省電。另外,如果速度調得很快,單幀位移可能超過球徑而直接「穿牆」,這時把一次移動拆成若干小步逐步檢查即可解決。