HTML5可以實現許多有趣的效果,其中之一就是煙花效果。下面是實現煙花效果的HTML5代碼:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>煙花效果</title> <style> canvas { background:black; } </style> </head> <body> <canvas id="canvas"></canvas> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var particles = []; var patriclesNum = 50; var w = 500; var h = 500; var colors = ['#f35d4f','#f36849','#c0d988','#6ddaf1','#f1e85b']; canvas.width = 500; canvas.height = 500; function Factory(){} Factory.prototype.draw = function(){ this.alpha -= 0.005; ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false); ctx.fillStyle = this.color+' '+this.alpha+')'; ctx.fill(); } function Particle(){} Particle.prototype = new Factory(); setInterval(function(){ ctx.globalCompositeOperation = 'source-over'; ctx.fillStyle = 'rgba(0,0,0,0.2)'; ctx.fillRect(0,0,w,h); ctx.globalCompositeOperation = 'lighter'; for(var i = 0;i< patriclesNum; i++){ if(Math.random() >0.5){ particles.push(new Particle()); } } for(var i = 0;i< particles.length; i++){ var p = particles[i]; p.draw(); if(p.alpha<= 0){ particles.splice(i, 1); } } }, 30); Particle.prototype.draw = function(){ this.x = Math.random() * w; this.y = Math.random() * h; this.r = Math.random() * 4 + 1; this.color = colors[Math.floor(Math.random() * colors.length)]; this.alpha = 1; this.velocity = { x: (Math.random() - 0.5) * 20, y: (Math.random() - 0.5) * 20 }; ctx.save(); ctx.translate(this.x, this.y); ctx.globalAlpha = this.alpha; ctx.beginPath(); for(var i = 0; i< 5; i++){ ctx.lineTo(0, this.r); ctx.translate(0, this.r); ctx.rotate((Math.PI*2 / 10)); ctx.lineTo(0, -this.r); ctx.translate(0, -this.r); ctx.rotate(-(Math.PI*6 / 10)); } ctx.lineTo(0, this.r); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); ctx.restore(); this.x += this.velocity.x; this.y += this.velocity.y; this.alpha -= 0.01; }; </script> </body> </html>
上一篇webpack3 css
下一篇html5實現貪吃蛇代碼