html5画布

it2026-01-05  9

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cs{ border:1px solid red; } </style> </head> <body> <canvas id="cs" width="800" height="500"></canvas> <script> window.onload = function(){ let cs = document.getElementById("cs"); let ctx = cs.getContext("2d"); function random(start,end){ if(!end){ return parseInt(Math.random() * (start + 1)); }else{ return parseInt(Math.random() * (end - start + 1) + start); } } class Bubble{ constructor(){ this.x = random(50,750); this.y = random(50,450); this.color = `rgb(${random(255)},${random(255)},${random(255)})`; this.r = 50; this.scale = 1;//放大或缩小的比例 this.direct = 1;//放大或缩小的方向 this.step = random(1,10) / 500;//放大缩小的速率 } draw(){ if(this.scale < 0){ this.direct = 1; }else if(this.scale > 1){ this.direct = -1; } this.scale += this.step * this.direct; ctx.save(); ctx.beginPath(); ctx.translate(this.x,this.y); ctx.scale(this.scale,this.scale); ctx.fillStyle = this.color; ctx.globalAlpha = this.scale; ctx.arc(0,0,this.r,0,2 * Math.PI); ctx.fill(); ctx.restore(); } } let bubbleAry = []; for(let i = 0;i < 20;i++){ bubbleAry.push(new Bubble()); }   setInterval(function(){ ctx.clearRect(0,0,800,500); for(let bubble of bubbleAry){ bubble.draw(); }   },50); } </script> </body> </html>

转载于:https://www.cnblogs.com/xiaozhou619/p/9867016.html

最新回复(0)