유동장 화면

Susan Sarandon
풀어 주다: 2024-10-03 20:18:29
원래의
528명이 탐색했습니다.

Flow Field Screen

바닐라 JS 및 HTML 캔버스를 사용한 동적 흐름 필드

추상적인 입자 애니메이션에 매료된 적이 있나요? 이러한 유동적이고 역동적인 시각적 효과는 일반 JavaScript와 HTML 캔버스 요소를 사용하는 놀랍도록 간단한 기술을 통해 얻을 수 있습니다. 이 기사에서는 수천 개의 입자에 애니메이션을 적용하여 자연스러운 움직임을 제공하는 흐름장을 만드는 과정을 자세히 설명합니다.

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;
}
로그인 후 복사

설명:

  • 여백과 패딩을 0으로 설정하면 캔버스가 전체 화면을 채우게 됩니다.
  • 검은색 배경은 흰색 입자와 좋은 대비를 제공합니다.

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() 함수를 재귀적으로 호출하여 애니메이션을 부드럽게 유지합니다.

결론

입자 및 효과 클래스를 세분화하여 바닐라 JavaScript만 사용하여 유동적이고 역동적인 흐름장 애니메이션을 만들었습니다. JavaScript의 삼각 함수와 결합된 HTML 캔버스의 단순성을 통해 이러한 매혹적인 시각 효과를 구축할 수 있습니다.

입자 수, 색상 또는 흐름장 공식을 자유롭게 활용하여 자신만의 독특한 효과를 만들어보세요!

위 내용은 유동장 화면의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!