HTML5煙花動態背景代碼是一種常用的網頁背景特效,它能夠讓網頁看起來更加生動和有趣。下面我們結合實例來介紹如何實現煙花動態背景。
<!-- 首先,在html文件中引入canvas元素,并設置寬高 --> <canvas id="fireworks" width="1200" height="800"></canvas> <!-- 接著,在js文件中編寫以下代碼 --> var canvas, ctx, W, H; var fireworks = []; function init() { canvas = document.getElementById("fireworks"); ctx = canvas.getContext("2d"); W = canvas.width; H = canvas.height; setInterval(draw, 20); createFireworks(); } function createFireworks() { fireworks.push(new Firework(W / 2, H, Math.random() * W, Math.random() * H / 2)); setTimeout(createFireworks, 800); } function draw() { var gradient = ctx.createLinearGradient(0, 0, 0, H); gradient.addColorStop(0, "black"); gradient.addColorStop(0.2, "pink"); gradient.addColorStop(1, "orange"); ctx.fillStyle = gradient; ctx.fillRect(0, 0, W, H); for (var i = 0; i< fireworks.length; i++) { fireworks[i].draw(); fireworks[i].update(); } } function Firework(xpos, ypos, xtarget, ytarget) { this.xpos = xpos; this.ypos = ypos; this.xtarget = xtarget; this.ytarget = ytarget; this.vx = Math.random() * 10 - 5; this.vy = Math.random() * -10 - 10; this.gravity = 0.2; this.color = "hsl(" + Math.random() * 360 + ", 50%, 50%)"; } Firework.prototype.draw = function() { ctx.beginPath(); ctx.fillStyle = this.color; ctx.arc(this.xpos, this.ypos, 5, 0, 2 * Math.PI); ctx.fill(); } Firework.prototype.update = function() { this.ypos += this.vy; this.vy += this.gravity; this.xpos += this.vx; if (this.ypos< this.ytarget) { fireworks.push(new Particle(this.xpos, this.ypos)); for (var i = 0; i< 10; i++) { fireworks.push(new Particle(this.xpos, this.ypos)); } } } function Particle(xpos, ypos) { this.xpos = xpos; this.ypos = ypos; this.vx = Math.random() * 10 - 5; this.vy = Math.random() * -10; this.gravity = 0.2; this.alpha = 1; this.color = "hsl(" + Math.random() * 360 + ", 50%, 50%)"; } Particle.prototype.draw = function() { ctx.beginPath(); ctx.fillStyle = this.color; ctx.arc(this.xpos, this.ypos, 2, 0, 2 * Math.PI); ctx.fill(); } Particle.prototype.update = function() { this.ypos += this.vy; this.xpos += this.vx; this.vy += this.gravity; this.alpha -= 0.01; if (this.alpha< 0) { fireworks.splice(fireworks.indexOf(this), 1); } } window.onload = init; <!-- 最后,在css文件中為canvas添加一些樣式 --> canvas { position: absolute; top: 0; left: 0; z-index: -1; }
在上述代碼中,我們首先在html文件中引入canvas元素,并設置寬高。然后在js文件中使用setInterval方法在canvas中畫出煙花效果,并使用setTimeout方法不斷生成煙花。最后在css文件中為canvas添加一些樣式,使其可以作為背景效果。