当前位置:首页 > JavaScript

js实现火焰算法

2026-02-02 22:47:43JavaScript

火焰算法实现基础

火焰算法(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)';

增加多色阶火焰效果:

js实现火焰算法

// 修改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上执行计算。

标签: 算法火焰
分享给朋友:

相关文章

排序算法 php实现

排序算法 php实现

以下是用PHP实现的常见排序算法,每种算法均附示例代码和简要说明: 冒泡排序 通过重复比较相邻元素并交换位置实现排序: function bubbleSort($arr) { $n…

react diff算法实现

react diff算法实现

React Diff 算法实现原理 React 的 Diff 算法(Reconciliation)是虚拟 DOM(Virtual DOM)更新的核心机制,通过高效比较新旧虚拟 DOM 树的差异,最小化…

用js来实现所有算法

用js来实现所有算法

在 JavaScript 中实现所有算法是一个庞大的任务,因为算法种类繁多,涵盖数据结构、排序、搜索、图论、动态规划等多个领域。以下是部分常见算法的 JavaScript 实现示例,供参考: 排序算…

用JS实现快速排序算法

用JS实现快速排序算法

快速排序的原理 快速排序是一种分治算法,通过选择一个基准元素(pivot)将数组分为两部分,一部分小于基准,另一部分大于基准,然后递归地对这两部分进行排序。 代码实现 function quickS…

js实现算法

js实现算法

JavaScript 实现常见算法的方法 排序算法 快速排序的实现: function quickSort(arr) { if (arr.length <= 1) return arr;…