Canvas 炫彩小球
生活随笔
收集整理的這篇文章主要介紹了
Canvas 炫彩小球
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Canvas 基礎應用
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title></title><style>* {margin: 0px;padding: 0px;}canvas {border: 1px solid #ccc;}</style></head><body><input type="number" id="ballNum"><button type="button" onclick="setBall()">設置小球半徑</button><br><canvas id="mycanvas"></canvas><script>var canvas = document.getElementById('mycanvas');var ctx = canvas.getContext('2d');canvas.width = window.innerWidth - 100;canvas.height = window.innerHeight - 100;function setBall() {var num = document.getElementById('ballNum');var value = parseInt(num.value);// 創建50個小球for (var i = 0; i < 50; i++) {new Ball(value);}// 定時器動畫setInterval(function() {// 清除畫布ctx.clearRect(0, 0, canvas.width, canvas.height);for (var i = 0; i < 50; i++) {ballArr[i].update();ballArr[i].render();}}, 10);}function Ball(r) {// 控制小球的x,y,這樣就不會超過屏幕this.x = parseInt(Math.random() * (canvas.width - r*2)) + r;this.y = parseInt(Math.random() * (canvas.height - r*2)) + r;this.r = r;this.color = getColor();// 初始速度不能為0do {this.dx = parseInt(Math.random() * 10) - 5;this.dy = parseInt(Math.random() * 10) - 5;} while (this.dx === 0 || this.dy === 0);// 把小球放入數組中存儲ballArr.push(this); // 獲取小球id,連線時只連比自己大的,這樣只有一條線this.index = ballArr.length - 1;}Ball.prototype.update = function() {this.x += this.dx;this.y += this.dy;// 當小球超出邊界時,改變方向,并改變顏色if (this.x < this.r || this.x > (canvas.width - this.r)) {this.dx = -this.dx;this.color = getColor();}if (this.y < this.r || this.y > (canvas.height - this.r)) {this.dy = -this.dy;this.color = getColor();}// 畫線邏輯for (var i = this.index; i < ballArr.length; i++) {// 如果小球的距離在一定范圍內,就連線if (Math.abs(ballArr[i].x - this.x) < 150 && Math.abs(ballArr[i].y - this.y) < 150) {ctx.strokeStyle = "#000";ctx.beginPath();var len = Math.sqrt(Math.pow(ballArr[i].x - this.x, 2) + Math.pow(ballArr[i].y - this.y, 2));// 根據距離,設置線的透明度ctx.globalAlpha = 10 / len;// 根據距離,設置線的寬度ctx.lineWidth = 150 / len;ctx.moveTo(this.x, this.y);ctx.lineTo(ballArr[i].x, ballArr[i].y);ctx.closePath();ctx.stroke();}}}// 渲染小球Ball.prototype.render = function() {ctx.beginPath();// 透明度ctx.globalAlpha = 1;// 畫小球ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);ctx.fillStyle = this.color;ctx.fill();} // 隨機生成顏色function getColor() {var colorStyle = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f';var colorArr = colorStyle.split(',');var color = '#';for (var i = 0; i < 6; i++) {color += colorArr[parseInt(Math.random() * colorArr.length)];}return color;}var ballArr = [];</script></body> </html>效果
南無阿彌陀佛,祝你新年吉祥!
總結
以上是生活随笔為你收集整理的Canvas 炫彩小球的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [POI2013]LUK-Triumph
- 下一篇: 报数游戏c语言,报数游戏-实战简单设计