今天給大家介紹一個html5制作的表白煙花效果,相信大家一定會被它的美麗和浪漫所吸引!
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>表白煙花特效</title> <style> canvas { z-index: -1; position: absolute; top: 0px; left: 0px; background-color: black; } </style> </head> <body> <canvas id="canvas"></canvas> <script> var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), W = canvas.width = window.innerWidth, H = canvas.height = window.innerHeight, particles = [], fireworks = [], gravity = 0.1; function Particle(x,y,color){ this.x = x; this.y = y; this.color = color; this.vx = Math.random()*10-5; this.vy = Math.random()*10-5; this.radius = 10; this.alpha = 1; this.gravity = 0.5; } Particle.prototype.draw = function(){ context.globalAlpha = this.alpha; context.fillStyle = this.color; context.beginPath(); context.arc(this.x,this.y,this.radius,0,Math.PI*2,false); context.closePath(); context.fill(); } Particle.prototype.update = function(){ this.x += this.vx; this.y += this.vy; this.vy += this.gravity; this.alpha -= 0.01; if(this.alpha <= 0){ particles.splice(i,1) } } function createFirework(){ var firework = { x: Math.random()*W, y: H, color: colors[Math.floor(Math.random()*colors.length)], particles: [] } for(var i = 0;i<30;i++){ var particle = new Particle(firework.x,firework.y,firework.color); firework.particles.push(particle); } fireworks.push(firework); } function drawFireworks(){ for(var i = 0;i<fireworks.length;i++){ var firework = fireworks[i]; for(var j = 0;j<firework.particles.length;j++){ firework.particles[j].draw(); firework.particles[j].update(); } } } function drawRain(){ for(var i = 0;i<100;i++){ var x = Math.random() * W, y = Math.random() * H, length = Math.random() * 0.6 + 0.2; context.beginPath(); context.moveTo(x,y); context.lineTo(x-length,y+length); context.closePath(); context.strokeStyle = "rgba(255,255,255,0.5)"; context.stroke(); } } var colors = ["red","blue","green","yellow","orange","purple","white"]; setInterval(function(){ context.clearRect(0,0,W,H); drawRain(); drawFireworks(); if(Math.random() < 0.05){ createFirework(); } },1000/60); window.onresize = function(){ W = canvas.width = window.innerWidth; H = canvas.height = window.innerHeight; } </script> </body> </html>
在這段代碼中,canvas標簽創建了一個煙花動畫畫布,使用了js來實現煙花的軌跡、顏色、速度等的控制,最后在窗口上不斷繪制煙花特效,使得整個頁面充滿了浪漫和幸福氣息。
上一篇html5煙花特效代碼
下一篇html5照片墻代碼