main

The origin of this experiment stems from my first days of seriously studying JavaScript while at school. I was wondering if I could animate a rotating gradient display. I saw that a gradient was an animatable (word?) option. So I did it! It was a red and blue gradient. Once I finished it, it was very mesmerizing. That was about it for this JavaScript experiment.\n\n Then recently, I wanted to do that experiment again. But this time, I would see if I could dynamically change colors constantly. I chose to use RGB color values, because I could use the number values easier than hex values. I had an incrementor that increased all the way to 255 and then reset back to 0 just to be modified again. Reseting the number back to zero consequently made a color jump that I did not want to happen. So then I had to make something that increment to 255 but then decrement to 0. So I set up a set of if statments that had a boolean condition to see if a number was growing or not.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const backgroundGradient = (() => {
    let grad = document.querySelector('body'),
        degree = 0,
        red = 200,
        green = 0,
        blue = 100,
        redup = true,
        greenup = false,
        blueup = false;

    const genRGBcolorSet1 = () => `${red} ${green} ${blue}`;
    const genRGBcolorSet2 = () => `${green} ${red} ${blue}`;

    const animateGradient = () => {
        grad.style.background = `linear-gradient(${degree}deg, rgb(${genRGBcolorSet1()}), rgb(${genRGBcolorSet2()}))`;
        degree++;

        if (red === 254) redup = false;
        if (red === 1) redup = true;

        redup ? red++ : red--;

        if (green === 254) greenup = false;
        if (green === 1) greenup = true;

        greenup ? green++ : green--;

        if (blue === 254) blueup = false;
        if (blue === 1) blueup = true;

        blueup ? blue++ : blue--;

        if (degree === 361) degree = 0;
    };
    setInterval(animateGradient, 100);
})();

You can see the code in this Github gist.