HTML
<canvas id="canvas" width="500" height="500" style="border: 1px solid #FF0000;"></canvas>
JS
1.獲取上下文
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
2.實現一個球類
1 class circle { 2 constructor() { 3 this.x = 25, 4 this.y = 25, 5 this.mx = Math.random()*5, 6 this.my = Math.random()*3, 7 this.radius = 25, 8 this.color = 'blue', 9 this.draw = function () { 10 ctx.beginPath(); 11 ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,true); 12 ctx.fillStyle = this.color; 13 ctx.fill(); 14 } 15 } 16 17 };
3.new一個球
let ball = new circle();
4.實現動畫函式
const move = (function () { // 清除畫布 ctx.clearRect(0,0, canvas.width, canvas.height); // 重新繪製圓 ball.draw(); // 移動圓 ball.x += ball.mx; // x座標遞增 ball.y += ball.my; // y座標遞增 // x軸座標加移動的距離大於畫布寬度(到達右邊界) 或 x軸座標加移動的距離等於0(到達左邊界) if (ball.x + ball.mx > canvas.width || ball.x + ball.mx < 0) { ball.mx = -ball.mx; // x軸座標遞減 }; // y軸座標加移動的距離大於畫布寬度(到達下邊界) 或 y軸座標加移動的距離等於0(到達上邊界) if (ball.y + ball.my > canvas.height || ball.y + ball.my < 0) { ball.my = -ball.my; // y軸座標遞減 }; // 遞迴呼叫當前方法 window.requestAnimationFrame(arguments.callee); })();