烟花代码可复制
时间: 2023-07-31 22:12:35 浏览: 128
2022新年烟花代码html(html制作新年烟花代码+带音效)
5星 · 资源好评率100%
我不确定你想要什么样的“烟花代码”,但我可以给你一个基本的 HTML、CSS 和 JavaScript 实现的例子,你可以复制粘贴到你的项目中进行测试。
HTML 代码:
```html
<html>
<head>
<title>烟花效果</title>
<style>
canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
</style>
</head>
<body>
<canvas></canvas>
<script src="fireworks.js"></script>
</body>
</html>
```
CSS 代码:
```css
body {
background-color: #000;
}
```
JavaScript 代码:
```javascript
// 烟花效果
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var particlesArray = [];
var hue = 120;
var mouse = {
x: canvas.width / 2,
y: canvas.height / 2
};
window.addEventListener("resize", function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
window.addEventListener("mousemove", function (event) {
mouse.x = event.clientX;
mouse.y = event.clientY;
});
function random(min, max) {
return Math.random() * (max - min) + min;
}
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = random(-5, 5);
this.vy = random(-15, -5);
this.gravity = 0.2;
this.hue = random(hue - 20, hue + 20);
this.brightness = random(50, 80);
this.alpha = 1;
this.decay = random(0.015, 0.03);
}
Particle.prototype.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
ctx.fillStyle = "hsla(" + this.hue + ", 100%, " + this.brightness + "%, " + this.alpha + ")";
ctx.fill();
};
Particle.prototype.update = function () {
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.alpha -= this.decay;
if (this.alpha <= 0) {
particlesArray.splice(particlesArray.indexOf(this), 1);
}
};
function createParticles() {
for (var i = 0; i < 20; i++) {
particlesArray.push(new Particle());
}
}
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particlesArray.length; i++) {
particlesArray[i].draw();
particlesArray[i].update();
}
if (particlesArray.length < 100) {
createParticles();
}
}
createParticles();
animate();
```
你可以将这些代码复制到一个文件夹中,将文件夹内的三个文件命名为 `index.html`、`style.css` 和 `fireworks.js`,然后在浏览器中打开 `index.html` 文件,就可以看到烟花效果了。
阅读全文