canvas圓形隨機漂浮效果
分享一段程式碼例項,它利用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 type="text/javascript"> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //瀏覽器寬高 var screenWidth = document.documentElement.clientWidth; var screenHeight = document.documentElement.clientHeight; canvas.width = screenWidth; //顯示螢幕的畫素 canvas.height = screenHeight; //顯示螢幕的高度 //隨機函式 function rand(min, max) { return Math.floor(Math.random() * (max - min) + min); } function Ball() { //半徑 this.r = rand(5, 100); //圓心 this.x = rand(this.r, screenWidth - this.r); this.y = rand(this.r, screenHeight - this.r); //顏色 this.color = "rgba(" + rand(0, 255) + "," + rand(0, 255) + "," + rand(0, 255) + "," + Math.random() + ")"; //速度 this.speedX = rand(1, 3) * (rand(0, 3) > 1 ? 1 : -1); this.speedY = rand(1, 4) * (rand(0, 3) > 1 ? 1 : -1); } //位置變化 Ball.prototype.move = function() { this.x += this.speedX; this.y += this.speedY; 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 < 20; 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>
相關文章
- JavaScript隨機漂浮碰壁效果JavaScript隨機
- canvas圓形時鐘效果Canvas
- canvas小球隨機漂浮碰撞程式碼例項Canvas隨機
- canvas實現的圓形時鐘效果Canvas
- HTML5畫布canvas隨機生成圓形和正方形HTMLCanvas隨機
- canvas繪製圓形框效果不填充內部Canvas
- canvas實現的圓形走動鐘錶效果Canvas
- canvas實現的隨機生成漂浮小球程式碼例項Canvas隨機
- canvas 繪製圓形Canvas
- canvas實現的圓形鐘錶效果程式碼例項Canvas
- 2D圓形隨機分佈隨機
- JavaScript隨機漂浮廣告詳解JavaScript隨機
- WebAssembly Demo之Canvas中隨機運動圓球WebCanvas隨機
- CSS圓形圖片效果CSS
- SVG圓形鐘錶效果SVG
- JavaScript圓形鐘錶效果JavaScript
- 圓形放大的hover效果
- canvas環形資料效果Canvas
- 自定義隨機顏色的圓形小球view隨手指移動隨機View
- canvas繪製多個圓圈效果Canvas
- canvas環形進度條效果Canvas
- 使用canvas繪製圓形進度條Canvas
- canvas的簡單圓形進度條Canvas
- html5中canvas繪製圓形HTMLCanvas
- 跟隨滾動條漂浮的返回頂部按鈕效果
- 隨機漂浮圖片廣告例項程式碼隨機
- canvas圓形進度條註釋超全Canvas
- css實現圓形、橢圓和半圓效果程式碼例項CSS
- canvas繪製圓盤走動鐘錶效果Canvas
- canvas繪製橢圓效果程式碼例項Canvas
- CSS3圓形進度條效果CSSS3
- canvas繪製圓形鐘錶程式碼例項Canvas
- canvas繪製實心圓形程式碼例項Canvas
- HTML5 Canvas使用路徑——繪製圓形HTMLCanvas
- html5利用canvas圓形和多邊形程式碼例項HTMLCanvas
- JavaScript動態圓形鐘錶效果詳解JavaScript
- CSS3圓形時鐘效果程式碼CSSS3
- css3動態圓形鐘錶效果CSSS3