使用js 画个动态火堆
时间: 2023-07-20 19:08:24 浏览: 45
好的,以下是一个使用 JavaScript 绘制动态火堆的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>动态火堆</title>
<style>
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 火堆颜色
const colors = ['#ffba08', '#faa307', '#f48c06', '#e85d04', '#dc2f02', '#d00000'];
// 火堆粒子
class Particle {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.velocity = {
x: Math.random() * 4 - 2,
y: Math.random() * 4 - 2
};
this.alpha = 1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.fill();
}
update() {
this.x += this.velocity.x;
this.y += this.velocity.y;
this.alpha -= 0.01;
this.radius -= 0.02;
}
}
// 火堆
class Fire {
constructor(x, y) {
this.x = x;
this.y = y;
this.particles = [];
}
createParticles() {
for (let i = 0; i < 50; i++) {
const radius = Math.random() * 10 + 10;
const color = colors[Math.floor(Math.random() * colors.length)];
this.particles.push(new Particle(this.x, this.y, radius, color));
}
}
update() {
for (let i = 0; i < this.particles.length; i++) {
this.particles[i].draw();
this.particles[i].update();
if (this.particles[i].alpha <= 0) {
this.particles.splice(i, 1);
}
}
}
}
// 创建火堆
const fire = new Fire(canvas.width / 2, canvas.height);
// 动画循环
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
fire.createParticles();
fire.update();
}
animate();
</script>
</body>
</html>
```
这个示例代码中包含了 `Particle` 粒子和 `Fire` 火堆两个类,通过创建多个粒子并不断更新它们的位置、透明度和大小来实现火焰效果。在 `animate` 函数中不断调用 `requestAnimationFrame` 方法,实现动态效果。