canvas實現的隨機生成漂浮小球程式碼例項
分享一段程式碼例項,它實現了隨機生成漂浮小球的功能。
程式碼例項如下:
[HTML] 純文字檢視 複製程式碼<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> <script> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var screenWidth = document.documentElement.offsetWidth; var screenHeight = document.documentElement.offsetHeight; canvas.width = screenWidth; canvas.height = screenHeight; //隨機函式 function rand(min, max) { return Math.floor(Math.random() * (max - min) + min); } function Ball() { this.r = rand(5, 30); //圓心 this.x = rand(this.r, screenWidth - this.r); this.y = rand(this.r, screenHeight - this.r); //顏色 this.color = "rgba(" + rand(0, 256) + "," + rand(0, 256) + "," + rand(0, 256) + "," + Math.random() + ")"; //速度 this.speedX = rand(1, 10); this.speedY = rand(1, 10); } Ball.prototype.move = function() { this.x += this.speedX * (rand(0, 2) > 1 ? 1 : -1); this.y += this.speedY * (rand(0, 2) > 1 ? 1 : -1); if (this.x >= screenWidth - this.r) { this.speedX *= -1; } if (this.x <= this.r) { this.speedX *= -1; } if (this.y >= screenHeight - this.r) { this.speedY *= -1; } if (this.y <= this.r) { this.speedY *= -1; } } Ball.prototype.draw = function() { ctx.beginPath(); ctx.fillStyle = this.color; ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); } var balls = []; for (var i = 0; i < 100; i++) { var ball = new Ball(); balls.push(ball); ball.draw(); } function move() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < balls.length; i++) { var ball = balls<i>; ball.draw(); ball.move(); } window.requestAnimationFrame(move); } move(); </script> </body> </html>
相關文章
- canvas小球隨機漂浮碰撞程式碼例項Canvas隨機
- canvas實現的彈力小球效果程式碼例項Canvas
- 隨機漂浮圖片廣告例項程式碼隨機
- canvas實現的小球四壁碰撞效果程式碼例項Canvas
- javascript實現的生成驗證碼隨機數程式碼例項JavaScript隨機
- jQuery實現的生成隨機密碼程式碼例項簡單介紹jQuery隨機密碼
- javascript生成隨機數程式碼例項JavaScript隨機
- js生成隨機數程式碼例項JS隨機
- canvas實現的刮刮樂程式碼例項Canvas
- 原生javascript實現的隨機生成4位字串程式碼例項JavaScript隨機字串
- canvas圓形隨機漂浮效果Canvas隨機
- canvas實現的美猴王程式碼例項Canvas
- canvas小球碰壁隨機運動Canvas隨機
- javascript生成不重複隨機數程式碼例項JavaScript隨機
- js實現的產生隨機數程式碼例項JS隨機
- 180行JavaScript程式碼實現的小球隨機移動程式碼JavaScript隨機
- canvas實現的驗證碼效果程式碼例項Canvas
- canvas實現的變幻線程式碼例項Canvas線程
- canvas實現的多邊形程式碼例項Canvas
- canvas實現的千輪眼程式碼例項Canvas
- canvas實現的鋸齒效果程式碼例項Canvas
- canvas實現的鐘表效果程式碼例項Canvas
- 前端學習程式碼例項-JavaScript 生成隨機數前端JavaScript隨機
- javascript生成指定位數隨機數程式碼例項JavaScript隨機
- 利用canvas實現的驗證碼效果程式碼例項Canvas
- javascript實現的m到n的隨機數程式碼例項JavaScript隨機
- canvas實現的貪吃蛇遊戲程式碼例項Canvas遊戲
- canvas實現的雪花飄落效果程式碼例項Canvas
- canvas實現的藍色雨滴效果程式碼例項Canvas
- canvas實現的圖片縮放程式碼例項Canvas
- canvas實現煙花燃放效果程式碼例項Canvas
- jquery小球碰撞效果程式碼例項jQuery
- js隨機生成信用卡卡號程式碼例項JS隨機
- canvas實現的簡單餅狀圖程式碼例項Canvas
- canvas實現的七巧板效果程式碼例項Canvas
- canvas實現的動態心形效果程式碼例項Canvas
- canvas實現的簡單塗鴉板程式碼例項Canvas
- canvas實現的五子棋程式碼例項Canvas