HTML煙花程序是一種非常有趣的web應用程序,它可以讓我們在網頁上觀看美麗的煙花效果。下面是一個簡單的HTML煙花程序代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML煙花程序</title> <style> canvas { width: 100%; height: 100%; } </style> </head> <body> <canvas id="fireworks"></canvas> <script> (function() { var canvas = document.getElementById('fireworks'); var ctx = canvas.getContext('2d'); var particles = []; var particleCount = 50; var colors = ['#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3']; var gravity = 0; canvas.width = window.innerWidth; canvas.height = window.innerHeight; function Particle() { this.x = canvas.width / 2; this.y = canvas.height; this.vx = Math.random() * 10 - 5; this.vy = -Math.random() * 5 - 5; this.color = colors[Math.floor(Math.random() * colors.length)]; this.radius = Math.random() * 5 + 2; this.gravity = 0.1; this.update = function() { this.x += this.vx; this.y += this.vy; this.vy += this.gravity; this.color = colors[Math.floor(Math.random() * colors.length)]; this.alpha = 1 - this.y / canvas.height; }; this.render = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.globalAlpha = this.alpha; ctx.fill(); }; } function createParticles() { for (var i = 0; i < particleCount; i++) { var particle = new Particle(); particles.push(particle); } } function updateParticles() { for (var i = 0; i < particles.length; i++) { particles[i].update(); } } function renderParticles() { for (var i = 0; i < particles.length; i++) { particles[i].render(); } } function loop() { ctx.clearRect(0, 0, canvas.width, canvas.height); createParticles(); updateParticles(); renderParticles(); window.requestAnimationFrame(loop); } window.requestAnimationFrame(loop); })(); </script> </body> </html>
在這個代碼中,我們使用了HTML5的<canvas>
標簽來創建一個畫布,然后使用JavaScript代碼在畫布上創建了一些粒子來模擬煙花效果。代碼中使用了多種變量和函數來實現這個效果,包括顏色數組、重力、粒子更新和渲染等。這個程序非常簡單易懂,可以讓任何人都能快速理解和使用。