原文鏈接:http://www.jianshu.com/p/c921d70812a5
著作權歸原作者所有:ToyLevom 簡書
<!DOCTYPE html> <html> <head> <meta charset= "utf-8"> <title></title> <!--<script src="jquery-1.9.1.min.js"></script>--> <style> * { margin: 0; padding: 0; } html,body { width: 100%; height: 100%; /*解決canvas的內聯塊的上下出現邊隙(浮動也可以解決)*/ /*font-size: 0;*/ } canvas { /*解決canvas的內聯塊的上下出現邊隙(浮動也可以解決)*/ display: block; } </style> </head> <body> <canvas width="500" height="500" id="cavas"></canvas> <script src="scripts/test.js"></script> </body> </html>
var cavas = document.getElementById("cavas"); var body = document.getElementsByTagName("body")[0]; var cxt = cavas.getContext("2d"); cavas.width = body.offsetWidth; cavas.height = body.offsetHeight; var cwidth = cavas.width; var cheight = cavas.height; //創建隨機函數 function random(max,min,notNum){ var result = parseInt(Math.random()*(max - min)+ min); if(result == notNum){ //指定不想要出現的隨機數 result++; } return result; } //隨機顏色函數 function randomColor() { return "rgba("+ random(0, 255) +","+ random(0, 255) +","+ random(0, 255) +","+ (Math.random() + 0.1).toFixed(2) +")"; } //創建構造函數 function Ball(x,y,r,speedX,speedY,color){ this.r = r||random(10,30) this.x = x||random(this.r, cwidth - this.r); this.y = y||random(this.r, cheight - this.r); this.color = color || randomColor(); this.speedX = speedX || random(-5, 5, 0); this.speedY = speedY || random(-5, 5, 0); //創建小球畫布 this.draw = function(){ cxt.fillStyle = this.color; cxt.beginPath(); cxt.arc(this.x,this.y,this.r,0,Math.PI*2,true); cxt.closePath(); cxt.fill(); } //創建小球移動 this.move = function(){ this.x += this.speedX;//速度是固定的 this.y += this.speedY; //如果小球在最邊上,則反彈回來 if(this.x > cwidth - this.r || this.x < this.r){ this.speedX = -this.speedX; } if(this.y > cheight - this.r || this.y < this.r){ this.speedY = - this.speedY; } this.draw(); } } //創建100個小球對象 var arrBall = []; for(var i=0; i < 100; i++){ var ball = new Ball(); arrBall.push(ball)//將生成的對象放進數組 } //小球移動 setInterval(function(){ cxt.clearRect(0, 0, cwidth , cheight); for(var i = 0,len = arrBall.length; i < len; i++){ arrBall[i].move(); } },16)