js实现火焰算法
火焰算法实现基础
火焰算法(Fire Effect)是一种模拟火焰燃烧效果的图形算法,常用于生成动态火焰视觉效果。在JavaScript中,可以通过Canvas或WebGL实现。
使用Canvas实现火焰效果
创建Canvas元素并初始化火焰数据数组:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const width = 200, height = 200;
canvas.width = width;
canvas.height = height;
// 火焰数据数组(每个像素的强度)
const firePixels = new Array(width * height).fill(0);
火焰更新逻辑
实现火焰的扩散和衰减效果:
function updateFire() {
for (let x = 0; x < width; x++) {
for (let y = 1; y < height; y++) {
const index = x + y * width;
// 火焰向上传播并衰减
firePixels[index - width] = Math.max(0,
(firePixels[index] +
firePixels[(x + 1) % width + y * width] +
firePixels[(x - 1 + width) % width + y * width] +
firePixels[x + ((y + 1) % height) * width]) / 4 - 0.1);
}
}
// 在底部添加新的火焰源
for (let x = 0; x < width; x++) {
firePixels[x + (height - 1) * width] = Math.random() > 0.5 ? 1 : 0;
}
}
渲染火焰效果
将火焰数据转换为可视化效果:
function renderFire() {
const imageData = ctx.createImageData(width, height);
for (let i = 0; i < firePixels.length; i++) {
const intensity = Math.min(1, firePixels[i]);
// 热色映射(红黄渐变)
const r = Math.min(255, intensity * 255);
const g = Math.min(255, intensity * 255 * 0.7);
const b = Math.min(255, intensity * 255 * 0.2);
imageData.data[i * 4] = r;
imageData.data[i * 4 + 1] = g;
imageData.data[i * 4 + 2] = b;
imageData.data[i * 4 + 3] = 255; // Alpha通道
}
ctx.putImageData(imageData, 0, 0);
}
动画循环
创建动画循环使火焰持续运动:
function animate() {
updateFire();
renderFire();
requestAnimationFrame(animate);
}
animate();
优化技巧
添加模糊效果增强真实感:
ctx.filter = 'blur(1px)';
增加多色阶火焰效果:
// 修改renderFire中的颜色计算
const colorMap = [
{r: 0, g: 0, b: 0}, // 黑色(无火焰)
{r: 255, g: 0, b: 0}, // 红色
{r: 255, g: 100, b: 0}, // 橙红色
{r: 255, g: 255, b: 0} // 黄色
];
function getFireColor(intensity) {
const level = Math.floor(intensity * (colorMap.length - 1));
return colorMap[level];
}
性能考虑
对于较大画布,建议使用WebGL实现以获得更好性能。核心算法原理相同,但通过着色器程序在GPU上执行计算。







