LoginSignup
1
0

【JavaScript】ストレス社会から逃れグラデーションの変化をずっと見ていたいあなたにおくるランダム生成した背景色のグラデーションをスムースに切り替えるスクリプト

Last updated at Posted at 2024-06-27

なんでもグラデーションがかっこいい!

私はウェブページで大事なのは配色だと思っています。

特にランダムで指定した色の組み合わせが偶然作り出すかっこいい組み合わせのグラデーションが好きです。

だからグラデーションの背景色をスムースに切り替えるスクリプトを作りました。

グラデーションをずっと見ていると落ち着く

気分がリラックスできて落ち着くことができる自然なグラデーション変化が楽しめるスクリプトはこちらです。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dissolving Gradient Background</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: hidden;
        }
        .gradient-background {
            width: 100%;
            height: 100%;
            position: fixed;
            top: 0;
            left: 0;
        }
        #gradient1 {
            z-index: 1;
        }
        #gradient2 {
            z-index: 2;
            opacity: 0;
        }
        @keyframes dissolve {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }
    </style>
</head>
<body>
    <div id="gradient1" class="gradient-background"></div>
    <div id="gradient2" class="gradient-background"></div>

    <script>
        function getRandomColor() {
            return `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`;
        }

        function createGradient() {
            const color1 = getRandomColor();
            const color2 = getRandomColor();
            const angle = Math.floor(Math.random() * 360);
            return `linear-gradient(${angle}deg, ${color1}, ${color2})`;
        }

        function updateGradient() {
            const gradient1 = document.getElementById('gradient1');
            const gradient2 = document.getElementById('gradient2');

            // 上層のグラデーションを設定
            gradient2.style.background = createGradient();

            // ディゾルブ効果をアニメーション
            gradient2.style.animation = 'dissolve 3s forwards';

            // アニメーション後、グラデーションを入れ替えてリセット
            setTimeout(() => {
                gradient1.style.background = gradient2.style.background;
                gradient2.style.opacity = 0;
                gradient2.style.animation = 'none';
            }, 3000);
        }

        // 初期グラデーション
        document.getElementById('gradient1').style.background = createGradient();
        document.getElementById('gradient2').style.background = createGradient();

        // 5秒ごとにグラデーションを更新
        setInterval(updateGradient, 5000);
    </script>
</body>
</html>

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