//css部分,給畫布設置邊框 <style> canvas { border:1px solid orange; } </style> //html 添加畫布 <canvas id="game" width="500" height="500"></canvas>
準備工做
先肯定所須要的屬性
小球的起始xy座標、R半徑、顏色、速度speedXY。css
//建立球構造函數 function ball() { this.r = this.rand(20); this.x = this.r; this.y = this.r; this.speedX = this.rand(10); this.speedY = this.rand(10); this.width = 0; this.height = 0; this.canvas = {}; this.color = 'rgb('+this.rand(255)+','+this.rand(255)+','+this.rand(255)+')'; this.init(); } //2.向原型鏈添加方法 ball.prototype = { init:function () { var game = document.getElementById('game'); this.canvas = game.getContext('2d'); this.width=game.width; this.height=game.height; }, rand:function (num) { return Math.floor(Math.random() * num+1); }, play:function () { this.x += this.speedX; this.y += this.speedY; if (this.x>this.width-this.r) { this.speedX = -this.speedX; } if (this.x<this.r) { this.speedX = Math.abs(this.speedX); } if (this.y>this.width-this.r) { this.speedY = -this.speedY; } if (this.y<this.r) { this.speedY = Math.abs(this.speedY); } this.canvas.beginPath(); this.canvas.fillStyle = this.color; this.canvas.arc(this.x, this.y, this.r, 0, 2 * Math.PI); this.canvas.fill(); } }; //3.建立100個小球 var arr = []; for (var i=0;i<100;i++) { arr[i] = new ball(); } //4.使用定時器,每一個30ms刷新屏幕 setInterval(function () { arr[0].canvas.clearRect(0,0,500,500); for (var i=0;i<arr.length;i++) { arr[i].play(); } },30)