HTML煙花代碼源碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML煙花效果</title> <style> body{ margin: 0; padding: 0; } canvas{ background-color: #050505; } </style> </head> <body> <canvas id="myCanvas"></canvas> <script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var particles = []; var particleCount = 30; var particleRadius = 3; function createParticles(){ for(var i = 0; i < particleCount; i++){ var x = canvas.width/2; var y = canvas.height-10; var vx = Math.random()*4-2; var vy = Math.random()*-8-8; var particle = new Particle(x,y,vx,vy); particles.push(particle); } } function drawParticles(){ for(var i in particles){ particles[i].draw(ctx); } } function updateParticles(){ for(var i in particles){ particles[i].update(); } } function clearCanvas(){ ctx.clearRect(0,0,canvas.width,canvas.height); } function draw(){ requestAnimationFrame(draw); clearCanvas(); drawParticles(); updateParticles(); } function Particle(x,y,vx,vy){ this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.draw = function(ctx){ ctx.beginPath(); ctx.fillStyle = "#fff"; ctx.arc(this.x,this.y,particleRadius,0,Math.PI*2,false); ctx.fill(); ctx.closePath(); } this.update = function(){ this.x += this.vx; this.y += this.vy; this.vy += 0.1; var bottomEdge = canvas.height-particleRadius; if(this.y >= bottomEdge){ this.y = bottomEdge; this.vy *= -0.6; } if(this.x < particleRadius || this.x >= canvas.width-particleRadius){ this.vx *= -1; } if(Math.abs(this.vx) < 0.1){ this.vx = 0; } } } createParticles(); draw(); </script> </body> </html>
上一篇java 變量和對象區別
下一篇html熱點圖代碼