新年烟花代码html
时间: 2023-12-23 10:26:52 浏览: 144
以下是一个简单的新年烟花代码的HTML和JavaScript实现,可以在网页中嵌入并运行:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>新年烟花</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var particles = [];
var particleCount = 100;
var particleSpeed = 2;
var particleSize = 3;
var colors = ["#f44336", "#e91e63", "#9c27b0", "#673ab7", "#3f51b5", "#2196f3", "#03a9f4", "#00bcd4", "#009688", "#4CAF50", "#8BC34A", "#CDDC39", "#FFEB3B", "#FFC107", "#FF9800", "#FF5722", "#795548"];
var mouseX = canvas.width / 2;
var mouseY = canvas.height / 2;
function Particle(x, y, speed, direction, size, color) {
this.x = x;
this.y = y;
this.vx = Math.cos(direction) * speed;
this.vy = Math.sin(direction) * speed;
this.size = size;
this.color = color;
}
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
};
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
};
function createParticles() {
for (var i = 0; i < particleCount; i++) {
var x = canvas.width / 2;
var y = canvas.height / 2;
var speed = Math.random() * particleSpeed;
var direction = Math.random() * Math.PI * 2;
var size = Math.floor(Math.random() * particleSize) + 1;
var color = colors[Math.floor(Math.random() * colors.length)];
particles.push(new Particle(x, y, speed, direction, size, color));
}
}
function updateParticles() {
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
p.update();
if (p.x < 0 || p.x > canvas.width || p.y < 0 || p.y > canvas.height) {
particles.splice(i, 1);
i--;
}
}
}
function drawParticles() {
for (var i = 0; i < particles.length; i++) {
particles[i].draw();
}
}
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
createParticles();
updateParticles();
drawParticles();
requestAnimationFrame(loop);
}
canvas.addEventListener("mousemove", function(event) {
mouseX = event.clientX;
mouseY = event.clientY;
});
loop();
</script>
</body>
</html>
```
这段代码使用HTML5的Canvas元素和JavaScript实现了一个简单的烟花效果。当页面加载时,会创建一定数量的粒子,并在Canvas上绘制它们。每个粒子都有一个随机的速度、方向、大小和颜色。当粒子移动到Canvas的边缘时,它会被从粒子数组中删除,以便创建新的粒子。
阅读全文