How to make animated gradients like Stripe

Jordi Enric - Aug 9 '20 - - Dev Community

Photo by Rafael Leão on Unsplash

Check stripe.com if you don't know what I am talking about.

I'm going to share with you a code snippet to create animated gradient canvas backgrounds.

<!DOCTYPE html>
<html>

<head>
    <title>Gradient</title>
    <meta charset="UTF-8" />

    <style>
        body {
            height: 400px;
            width: 500px;
        }

        canvas {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="32px" height="32px">

        <script>
            const canvas = document.getElementById('canvas');
            const context = canvas.getContext('2d');
            let time = 0;

            const color = function (x, y, r, g, b) {
                context.fillStyle = `rgb(${r}, ${g}, ${b})`
                context.fillRect(x, y, 10, 10);
            }
            const R = function (x, y, time) {
                return (Math.floor(192 + 64 * Math.cos((x * x - y * y) / 300 + time)));
            }

            const G = function (x, y, time) {
                return (Math.floor(192 + 64 * Math.sin((x * x * Math.cos(time / 4) + y * y * Math.sin(time / 3)) / 300)));
            }

            const B = function (x, y, time) {
                return (Math.floor(192 + 64 * Math.sin(5 * Math.sin(time / 9) + ((x - 100) * (x - 100) + (y - 100) * (y - 100)) / 1100)));
            }

            const startAnimation = function () {
                for (x = 0; x <= 30; x++) {
                    for (y = 0; y <= 30; y++) {
                        color(x, y, R(x, y, time), G(x, y, time), B(x, y, time));
                    }
                }
                time = time + 0.03;
                window.requestAnimationFrame(startAnimation);
            }

            startAnimation();


        </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

It's based on the code from
https://www.html5canvastutorials.com/advanced/html5-canvas-animated-gradient-background/

I just changed some things to make it more readable. Try to play with it to find out how it's doing it. It's really fun and not that hard.

Also if you go to Stripe.com/us and do the Konami Code (up, up, down, down, left, right, left, right, b, a) you will find hidden controls play with the animation.

Follow me on Twitter if you want to see more cool front end stuff :)

Have a good day ✌✌

. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player