標籤:cto canvas color http func apu glob 建立 cap
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 <style>10 /* #cs {11 border: 1px solid rebeccapurple;12 } */13 </style>14 </head>15 16 <body>17 <canvas id="cs" width="1200" height="600"></canvas>18 19 <script>20 window.onload = function () {21 let cs = document.getElementById(‘cs‘);22 let ab = cs.getContext(‘2d‘);23 function random(min, max) {24 return parseInt(Math.random() * (max - min + 1) + min);25 }26 class Bubble {27 constructor() {28 this.x = random(50, 950);29 this.y = random(50, 550);30 this.r = 50;31 this.color = `rgb(${random(0,255)},${random(0,255)},${random(0,255)})`;32 this.scale = 1;//放大縮小的比列33 this.direct = 1;//放大縮小的方向34 this.step = random(1, 10) / 500;//放大縮小的速率35 }36 draw() {37 if (this.scale < 0) {38 this.direct = 1;39 } else if (this.scale > 1) {40 this.direct = -1;41 }42 this.scale += this.step * this.direct;43 ab.save();//儲存轉換狀態44 ab.beginPath();//一個新的路徑45 ab.translate(this.x, this.y);46 ab.scale(this.scale, this.scale);//開始放大縮小47 ab.arc(0, 0, this.r, 0, 2 * Math.PI);48 ab.fillStyle = this.color;//背景顏色 49 ab.globalAlpha = this.scale;//透明50 ab.fill();51 ab.restore();//恢複畫布原點52 }53 }54 let arr=[];//建立空數組55 for(let i=0;i<50;i++){56 arr.push(new Bubble());//添加數組57 }58 setInterval(function(){59 ab.clearRect(0,0,1000,600);//清除之前的內容60 for(let bum of arr){//遍曆數組61 bum.draw();62 }63 },50)64 65 }66 </script>67 </body>68 69 </html>
用JavaScript編寫氣泡