html动态爱心烟花代码可复制
时间: 2023-10-21 19:05:00 浏览: 136
以下是一个简单的 HTML 动态爱心烟花代码,你可以复制并在浏览器中运行:
```html
<!DOCTYPE html>
<html>
<head>
<title>动态爱心烟花</title>
<style>
body {
background-color: black;
}
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var particles = [];
var particleCount = 100;
var particleRadius = 3;
var colors = ["#FF1461", "#18FF92", "#5A87FF", "#FBF38C"];
function Particle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.speed = {
x: -1 + Math.random() * 2,
y: -3.5 + Math.random() * 2
};
this.gravity = 0.1;
this.opacity = 1;
this.fadeOut = 0.01;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.opacity;
ctx.fill();
ctx.closePath();
};
Particle.prototype.update = function() {
this.speed.y += this.gravity;
this.x += this.speed.x;
this.y += this.speed.y;
this.opacity -= this.fadeOut;
};
function createParticles(x, y) {
for (var i = 0; i < particleCount; i++) {
var color = colors[Math.floor(Math.random() * colors.length)];
particles.push(new Particle(x, y, particleRadius, color));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, innerWidth, innerHeight);
for (var i = 0; i < particles.length; i++) {
particles[i].draw();
particles[i].update();
if (particles[i].opacity <= 0) {
particles.splice(i, 1);
}
}
}
canvas.addEventListener("click", function(event) {
createParticles(event.clientX, event.clientY);
});
animate();
</script>
</body>
</html>
```