通过粒子动画在canvas中可视化向量场

向量场是把空间中的每一点指派到一个向量的映射,通过向量场可以对速度、磁力、流体运动和梯度等进行建模。为了方便快捷地在不同设备上展示向量场,本文在canvas中部分实现了向量场的流粒子动画,并加入了粒子着色功能以展示向量场的其他标量性质。

使用方法

复制下面的代码为html文件,更改createVectorField函数以更改向量场,可按需修改其他参数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vector Field</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #000;
        }
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
</body>
<script src="https://cdn.jsdelivr.net/gh/ycythu/assets@main/js/vector_field/VectorFieldAnimeFull.min.js"></script>
<script type="text/javascript">
    const MAX_PARTICLE_AGE = 100;       // 粒子寿命
    const PARTICLE_MULTIPLIER = 10.0;   // 粒子密度
    const FRAME_RATE = 25;              // 刷新间隔(ms)
    const LINE_WIDTH = 1.0;             // 线宽
    const EVOLVE_STEP = 0.5;            // 步长
    const COLORMAP = [                  // 颜色图
        [58, 76, 192],
        [103, 136, 237],
        [153, 186, 254],
        [200, 215, 239],
        [237, 208, 193],
        [246, 167, 137],
        [225, 104, 82],
        [179, 3, 38]
    ];
    function createVectorField() {
        return {
            interpolate: (x, y) => {
                x = (x - bounds.width / 2) / (bounds.height /2);    // 等效x坐标
                y = (y - bounds.height / 2) / (bounds.height /2);   // 等效y坐标
                const u = 3 * (x * y) / (x * x + y * y);            // 向量场x分量
                const v = 3 * (y * y) / (x * x + y * y) - 1;        // 向量场y分量
                const norm = Math.sqrt(u * u + v * v);
                const colorParam = norm;                            // 着色依据
                return [u, v, norm, colorParam];
            }
        };
    }
    const canvas = document.getElementById("canvas");
    const dpr = window.devicePixelRatio || 1;
    const ctx = initializeCanvas(canvas, dpr);
    const bounds = {
        x: 0,
        y: 0,
        width: canvas.width / dpr,
        height: canvas.height / dpr
    };
    const particleCount = Math.round(bounds.width * PARTICLE_MULTIPLIER);
    const particles = Array.from({ length: particleCount }, () => randomizeParticle({}));
    const vectorField = createVectorField();
    const vectorColorRange = calculateColorLim(vectorField);
    const vectorColorScale = calculateColorScale(255, vectorColorRange, COLORMAP);
    frame(particles, vectorField, vectorColorScale, ctx);
</script>
</html>

示例

向量场散度的可视化

下图展示了向量场

\[\left\langle\sin(\pi x+\pi y),\cos(\pi x-\pi y-\frac\pi 2)\right\rangle\]

的可视化结果。不同颜色代表了散度不同的区域,红色代表散度为正,蓝色代表散度为负。

向量场旋度的可视化

下图展示了向量场

\[\left\langle\frac{3xy}{x^2+y^2},\frac{3y^2}{x^2+y^2}-1\right\rangle\]

的可视化结果。不同颜色代表了旋度不同的区域,红色代表旋度为正(逆时针旋转),蓝色代表旋度为负(顺时针旋转)。