彈跳球是入門 Canvas 遊戲很好的一道練習題。看似簡單,但裡面藏著座標系、速度向量、邊界碰撞與重繪時機幾個基本觀念,把它寫通,後續做磚塊、打靶之類的遊戲都會順手很多。

程式的開頭先把場景參數寫清楚。要注意一個容易搞混的點:球的座標指的是球心,而不是左上角。因此計算邊界時必須把半徑扣掉,否則球會有一半跑出牆外才反彈。
// 箱子 var box_x=0, box_y=0; var box_width=300, box_height=300; // 球(球心定位) var ball_x=10, ball_y=10; var ball_radius=10; var ball_vx=5, ball_vy=3; // 速度向量 // 有效活動範圍=箱子邊界各減一個半徑 var box_bound_left = box_x + ball_radius; var box_bound_right = box_x + box_width - ball_radius; var box_bound_top = box_y + ball_radius; var box_bound_bottom = box_y + box_height - ball_radius; var ctx;
載入時取得 2D context,設定線寬與填色,然後用 setInterval 每 100 毫秒推進一格。這裡用固定間隔而非 requestAnimationFrame,好處是邏輯簡單、行為可預期;缺點是幀率與螢幕更新不同步,正式專案建議改用 requestAnimationFrame。
function init() {
ctx = document.getElementById('canvas').getContext('2d');
ctx.lineWidth = ball_radius;
ctx.fillStyle = "rgb(200,0,50)";
move_ball();
setInterval(move_ball, 100);
}
每次移動前先算「下一個位置」,逐一檢查是否越界。若越界,就把該軸的速度取負號,並把座標夾回邊界上,避免球貼著牆邊來回抖動。
function move_and_check() {
var cur_ball_x = ball_x + ball_vx;
var cur_ball_y = ball_y + ball_vy;
if (cur_ball_x < box_bound_left) { ball_vx = -ball_vx; cur_ball_x = box_bound_left; }
if (cur_ball_x > box_bound_right) { ball_vx = -ball_vx; cur_ball_x = box_bound_right; }
if (cur_ball_y < box_bound_top) { ball_vy = -ball_vy; cur_ball_y = box_bound_top; }
if (cur_ball_y > box_bound_bottom){ ball_vy = -ball_vy; cur_ball_y = box_bound_bottom; }
ball_x = cur_ball_x;
ball_y = cur_ball_y;
}
每一幀的繪製流程是:先清空整個區域,再更新位置,然後畫球,最後畫框線。順序調動就會出現殘影。
function move_ball() {
ctx.clearRect(box_x, box_y, box_width, box_height);
move_and_check();
ctx.beginPath();
ctx.arc(ball_x, ball_y, ball_radius, 0, Math.PI*2, true);
ctx.fill();
ctx.strokeRect(box_x, box_y, box_width, box_height);
}
<html> <head> <meta charset=utf-8> <title>跳跳球</title> <script> /* 上述 box、ball 變數與 init、move_ball、move_and_check 皆置於此 */ </script> </head> <body onLoad="init()"> <canvas id="canvas" width="400" height="400"/> </body> </html>
想讓它更有趣,可以從幾個方向下手:改變 ball_vx 與 ball_vy 的相對大小讓角度不再呆板;加入重力讓 ball_vy 每幀遞增,模擬真實落地;或在碰撞時依入射角做向量反射,取代單純取負號。這些改動都不需要動到主結構,是理解向量運算很好的起點。