LoginSignup
0
0

More than 1 year has passed since last update.

【React】徐々に組み上がっていく背景イメージを実装する

Last updated at Posted at 2021-09-26

概要

アニメーションで徐々に組み上がっていく背景イメージを実装します。
JS Animationとありますが、使用するのはCSS Animationです。

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

本記事は、以下の動画をReactで実装したものです。

スタイリングには、emotion/css(CSS in JS)を使用しています。

実装

import React, { VFC } from 'react';
import { css, keyframes } from '@emotion/css';

export const AnimatedBackgroundImage: VFC = () => {
    const bloks = 400

    return (
        <div className={styles.container}>
            <h2 className={styles.title}>JS Animation</h2>
            <div className={styles.banner}>
                {[...Array(bloks)].map((_, i) => (
                    <div key={i} className={styles.block(i * 0.05)}></div>
                ))}
            </div>
        </div>
    )
}

const animations = {
    animate: keyframes`
    0% {
      opacity: 0;
      transform: scale(0) translateY(1000px);
    }
    50% {
      opacity: 1;
      background: url('/assets/bg.jpg');
      background-position: center;
      background-attachment: fixed;
    }
    100% {
      opacity: 1;
      transform: scale(1) translateY(0);
      background: url('/assets/bg.jpg');
      background-position: center;
      background-attachment: fixed;
    }
  `
}

const styles = {
    container: css`
        position: relative;
        width: 100vw;
        height: 100vh;
        background-color: #333;
        display: flex;
        justify-content: center;
        align-items: center;
    `,
    title: css`
        position: absolute;
        font-size: 10vw;
        color: #fff;
        font-weight: 700;
    `,
    banner: css`
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        display: flex;
        flex-wrap: wrap;
    `,
    block: (delay: number) => css`
        position: relative;
        display: block;
        width: 5vw;
        height: 5vh;
        animation: ${animations.animate} 0.75s ease-in-out ${delay}s forwards;

        &:nth-child(even) {
            animation-duration: 1s;
        }
        &:nth-child(7n + 3) {
            animation-duration: 2.5s;
        }
        &:nth-child(7n + 7) {
            animation-duration: 1.5s;
        }
    `
}
  • アニメーション実行時に、イメージを固定しておくのがポイントです。
background-position: center;
background-attachment: fixed;

0
0
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
0
0