LoginSignup
10
2

More than 1 year has passed since last update.

【React】particles.js で動く背景を作る

Last updated at Posted at 2021-09-11

概要

particles.jsを使うと、背景が動くちょっと面白いサイトを作ることができます。

output(video-cutter-js.com) (3).gif

公式デモサイトで、パラメーターをいじりながらアニメーションを試すことができます。

環境

  • React - 17.0.2
  • TypeScript - 4.4.2
  • react-particles-js - 3.5.3
  • npm - 7.23.0

インストール

プロジェクトフォルダを作成して、Create React Appでプロジェクトを作成します。

cmd
npx create-react-app . --template typescript

react-particles-jsをインストールします。

cmd
npm i react-particles-js

react-particles-jsがReact(17.x)に対応していない場合、--forceオプションを付けてインストールできます。

実装

コーディング

コーディングはとても簡単です。
スタイリングは、CSS-in-JSとしてemotionを使っています。

import React, { VFC } from 'react';
import Particles from 'react-particles-js';
import { IOptions, RecursivePartial } from 'tsparticles';
import { css } from '@emotion/css';
import ParticlesParams from '../assets/particles-default.json';

export const CustomParticles: VFC = () => {
    return (
        <Particles
            className={styles.particles}
            params={ParticlesParams as RecursivePartial<IOptions>}
        />
    )
}

const styles = {
    particles: css`
        position: absolute;
        width: 100%;
        height: 100%;
    `
}

設定

paramsとして、インポートしたjsonファイルを指定しています。
このjsonファイルで、色やノードの大きさ、マウス操作時のアニメーションなどの設定を行います。
これらの設定は、公式デモで試しながら調整することができます。また、その設定をjsonファイルとしてエクスポートすることができます。

スクリーンショット 2021-09-11 221947.png

設定のテンプレート

公式デモにはいくつか設定のテンプレートが用意されています。
例えば、[Snow]を選択すると、雪が降っているようなアニメーションになります。
スクリーンショット 2021-09-11 222658.png

まとめ

アニメーションはいざ実装しようとすると複雑になりがちなので、particles.jsのような簡単に使うことのできるパッケージは本当にありがたいです。
何より使ってて楽しいです:upside_down:

10
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
2