近年來,HTML5技術(shù)不斷發(fā)展,更多的新特效被開發(fā)出來。其中,煙花燃放特效備受歡迎。本文將分享一份HTML5煙花燃放特效代碼,讓你的網(wǎng)頁更具魅力。
//HTML代碼 <div id="fireworks-container"> <canvas id="fireworks-canvas"></canvas> </div> //JavaScript代碼 var fireworks = { elem: null, canvas: null, ctx: null, on: false, particles: [], init: function(x, y, elem){ this.elem = elem; this.canvas = elem.children('#fireworks-canvas')[0]; this.canvas.width = x; this.canvas.height = y; this.ctx = this.canvas.getContext('2d'); this.start(); }, start: function(){ this.on = true; this.loop(); }, stop: function(){ this.on = false; }, loop: function(){ if(this.on){ requestAnimationFrame(fireworks.loop.bind(this)); } this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.particles.forEach(function(particle){ particle.update(); }); this.createParticles(); }, createParticles: function(){ var particlesCount = Math.floor(Math.random()*10)+1; for(var i=0; i<particlesCount; i++){ this.particles.push(new Particle(this.canvas.width/2, this.canvas.height, this.ctx)); } } }; function Particle(x, y, ctx){ var colors = ['#f4429e', '#f44141', '#f4de41', '#41f49d', '#4178f4'];//煙花顏色 this.x = x; this.y = y; this.color = colors[Math.floor(Math.random()*colors.length)]; this.radius = 5; this.ctx = ctx; this.life = Math.floor(Math.random()*50)+70;//煙花生命值隨機(jī) this.vx = Math.floor(Math.random()*(6-(-6)+1)+(-6));//隨機(jī)速度 this.vy = Math.floor(Math.random()*(6-4+1)+4); this.gravity = 0.2;//重力 this.opacity = 1; this.update = function(){ this.opacity -= 1/this.life; if(this.opacity < 0){ this.opacity = 0; } this.vy -= this.gravity; this.x += this.vx; this.y -= this.vy; this.ctx.beginPath(); this.ctx.fillStyle = 'rgba('+parseInt(this.color.substr(1,2), 16)+','+parseInt(this.color.substr(3,2), 16)+','+parseInt(this.color.substr(5,2), 16)+','+this.opacity+')'; this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false); this.ctx.closePath(); this.ctx.fill(); } } //調(diào)用方法 fireworks.init(screen.width, screen.height, $('#fireworks-container'));
這段代碼使用了HTML5的canvas標(biāo)簽和JavaScript語言。當(dāng)調(diào)用init方法時(shí),頁面就會(huì)出現(xiàn)一系列煙花飛舞的效果。這個(gè)示例中,煙花顏色、形狀、運(yùn)動(dòng)軌跡等都是隨機(jī)生成的,使得每次煙花效果都不同。
總之,這份HTML5煙花特效代碼簡單易懂,可以在網(wǎng)頁中增添不少趣味。你也可以根據(jù)自己的需求和創(chuàng)意修改代碼,創(chuàng)造出更加獨(dú)特的效果。