首页  >  文章  >  web前端  >  流场屏幕

流场屏幕

Susan Sarandon
Susan Sarandon原创
2024-10-03 20:18:29528浏览

Flow Field Screen

使用 Vanilla JS 和 HTML Canvas 的动态流场

您是否曾经被抽象的粒子动画迷住过?这些流动的动态视觉效果可以通过使用纯 JavaScript 和 HTML canvas 元素的极其简单的技术来实现。在本文中,我们将分解创建一个流场的过程,该流场可以为数千个粒子提供动画,让它们自然运动。

1. 设置项目

首先,我们需要三个文件:一个用于设置画布的 HTML 文件、一个用于样式设置的 CSS 文件以及一个用于处理逻辑的 JavaScript 文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flow Fields</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <canvas id="canvas1"></canvas>
    <script src="script.js"></script>
</body>
</html>

解释:

  • 我们定义一个我们所有动画将发生的元素。
  • styles.css 将链接到画布样式。
  • 主要动画逻辑包含在 script.js 中。

2. 使用 CSS 设置画布样式

让我们添加一个简单的样式,为画布提供黑色背景,并确保删除所有内边距和边距。

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

canvas {
    background-color: black;
}

解释:

  • 将边距和填充设置为零可确保画布填满整个屏幕。
  • 黑色背景与白色颗粒形成良好的对比。

3. 粒子类:创造魔法

Particle类是动画的核心所在。每个粒子在画布上移动,留下其过去位置的痕迹,创造流动的效果。

class Particle {
    constructor(effect) {
        this.effect = effect;
        this.x = Math.floor(Math.random() * this.effect.width);
        this.y = Math.floor(Math.random() * this.effect.height);
        this.speedModifier = Math.floor(Math.random() * 5 + 1);
        this.history = [{ x: this.x, y: this.y }];
        this.maxLength = Math.floor(Math.random() * 200 + 10);
        this.timer = this.maxLength * 2;
        this.colors = ['#4C026B', '#8E0E00', '#9D0208', '#BA1A1A', '#730D9E'];
        this.color = this.colors[Math.floor(Math.random() * this.colors.length)];
    }

    draw(context) {
        context.beginPath();
        context.moveTo(this.history[0].x, this.history[0].y);
        for (let i = 1; i < this.history.length; i++) {
            context.lineTo(this.history[i].x, this.history[i].y);
        }
        context.strokeStyle = this.color;
        context.stroke();
    }

    update() {
        this.timer--;
        if (this.timer >= 1) {
            let x = Math.floor(this.x / this.effect.cellSize);
            let y = Math.floor(this.y / this.effect.cellSize);
            let index = y * this.effect.cols + x;
            let angle = this.effect.flowField[index];

            this.speedX = Math.cos(angle);
            this.speedY = Math.sin(angle);
            this.x += this.speedX * this.speedModifier;
            this.y += this.speedY * this.speedModifier;

            this.history.push({ x: this.x, y: this.y });
            if (this.history.length > this.maxLength) {
                this.history.shift();
            }
        } else if (this.history.length > 1) {
            this.history.shift();
        } else {
            this.reset();
        }
    }

    reset() {
        this.x = Math.floor(Math.random() * this.effect.width);
        this.y = Math.floor(Math.random() * this.effect.height);
        this.history = [{ x: this.x, y: this.y }];
        this.timer = this.maxLength * 2;
    }
}

解释:

  • 构造函数:每个粒子都用随机位置和移动速度初始化。历史数组跟踪过去的位置以创建轨迹。
  • draw():该函数根据粒子的历史记录绘制粒子的路径。粒子留下彩色轨迹,增加了视觉效果。
  • update():这里,通过计算与流场的角度来更新粒子的位置。速度和方向由三角函数控制。
  • reset():当粒子完成其轨迹时,它会重置到新的随机位置。

4.效果类:组织动画

Effect 类处理粒子的创建和流场本身,它控制粒子的运动。

class Effect {
    constructor(canvas) {
        this.canvas = canvas;
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        this.particles = [];
        this.numberOfParticles = 3000;
        this.cellSize = 20;
        this.flowField = [];
        this.curve = 5;
        this.zoom = 0.12;
        this.debug = true;
        this.init();
    }

    init() {
        this.rows = Math.floor(this.height / this.cellSize);
        this.cols = Math.floor(this.width / this.cellSize);
        for (let y = 0; y < this.rows; y++) {
            for (let x = 0; x < this.cols; x++) {
                let angle = (Math.cos(x * this.zoom) + Math.sin(y * this.zoom)) * this.curve;
                this.flowField.push(angle);
            }
        }
        for (let i = 0; i < this.numberOfParticles; i++) {
            this.particles.push(new Particle(this));
        }
    }

    drawGrid(context) {
        context.save();
        context.strokeStyle = 'white';
        context.lineWidth = 0.3;
        for (let c = 0; c < this.cols; c++) {
            context.beginPath();
            context.moveTo(c * this.cellSize, 0);
            context.lineTo(c * this.cellSize, this.height);
            context.stroke();
        }
        for (let r = 0; r < this.rows; r++) {
            context.beginPath();
            context.moveTo(0, r * this.cellSize);
            context.lineTo(this.width, r * this.cellSize);
            context.stroke();
        }
        context.restore();
    }

    render(context) {
        if (this.debug) this.drawGrid(context);
        this.particles.forEach(particle => {
            particle.draw(context);
            particle.update();
        });
    }
}

解释:

  • 构造函数:初始化画布尺寸、粒子数量、流场。
  • init():通过组合每个网格单元的三角函数来计算流场的角度。该场影响粒子的移动方式。
  • drawGrid():绘制将画布划分为单元格的网格,调试时使用。
  • render():调用每个粒子的绘制和更新方法,以在画布上为粒子设置动画。

5. 通过动画循环让它变得栩栩如生

为了让一切正常工作,我们需要一个动画循环来不断清除画布并重新渲染粒子:

const effect = new Effect(canvas);

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    effect.render(ctx);
    requestAnimationFrame(animate);
}
animate();

解释:

  • clearRect():清除每一帧上的画布,以避免覆盖之前的帧。
  • requestAnimationFrame:通过递归调用 animate() 函数来保持动画流畅。

结论

通过分解 Particle 和 Effect 类,我们仅使用普通 JavaScript 创建了流体和动态流场动画。 HTML 画布的简单性与 JavaScript 的三角函数相结合,使我们能够构建这些令人着迷的视觉效果。

随意使用粒子数、颜色或流场公式来创建您自己的独特效果!

以上是流场屏幕的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn