css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <canvas id="scene"></canvas>
            
          
!
            
              html, body, canvas {
  font-size:0;
  padding:0;
  margin:0;
  border:none
}

canvas {
  width:100vw;
  height:100vh;
}
            
          
!
            
              'use strict';

var FastRandom = function()
{
    var me = this;

    var stack = [];
    var index = 0;
    var max   = 1000;

    this.nextFloat = function()
    {
        if (index === max) {
            index = parseInt(Math.random() * (max - 1));
        }

        return stack[index++];
    };

    this.nextRealFloat = function()
    {
        return Math.random();
    };

    this.nextInt = function(min, max)
    {
        return parseInt((max - min) * me.nextFloat() + min);
    };

    this.nextRealInt = function(min, max)
    {
        return parseInt((max - min) * me.nextRealFloat() + min);
    };

    !function(){
        for (var i = 0; i < max; i++) {
            stack.push(Math.random());
        }
    }();
};

var Rain = function()
{
    var me = this;

    var rainCount = 5000;
    var starCount = 1000;

    var canvas;
    var engine;

    var width;
    var height;

    var midWidth;
    var midHeight;
    var debug = [];

    var color = {
        sun1    : '#7a2013',
        sun2    : '#302661',
        sun3    : '#05090f',
        sunMidIn  : '#c29b48',
        sunMidOut : '#928b18',
        // sunIn     : '#c2bb48',
        // sunOut    : '#9a4033',
        // sunMidIn  : '#f2eb78',
        // sunMidOut : '#c2bb48',
        mountainTop : 0x606060,
        mp : [
            //0
            0x0,
            0x030303,
            0x060606,
            //1
            0x111111,
            0x131313,
            0x161616,
            //2
            0x222222,
            0x262626,
            0x292929
        ],
        mountain  : [
            '#444',
            '#333',
            '#222'
            // '#5a2033',
            // '#4a1023',
            // '#3a0013'
        ],
        mountainGradients : [
            ['#444', '333'],
            ['#333', '222'],
            ['#222', '111']
        ]
    };

    var sunGradient;
    var sunMidGradient;

    var mountains;
    var mountainParts;
    var rain;
    var rainParts = 5;
    var rainColor = [0xff, 0x44];

    var mousePos = 0.5;
    var random;

    var tickCounter   = 0;
    var gravityPoints = [];
    var gravityProcc;
    var distanceNormalizer;

    var stars;
    var starLayer     = 5;
    var starColorDiff = 0xa0;
    var starColors;

    var visibility = {
        current : 0.2,
        target  : 0.2
    };

    var mainWind = {
        current : 0,
        target  : 0
    };

    var createSunGradient = function()
    {
        sunGradient = engine.createRadialGradient(midWidth, height * 2, 0, midWidth, height * 2, height * 2);
        sunGradient.addColorStop(0.6, color.sun1);
        sunGradient.addColorStop(0.8, color.sun2);
        sunGradient.addColorStop(1, color.sun3);

        sunMidGradient = engine.createRadialGradient(midWidth, midHeight, 0, midWidth, midHeight, parseInt(width / 10));
        sunMidGradient.addColorStop(0, color.sunMidIn);
        sunMidGradient.addColorStop(1, color.sunMidOut);
    };

    var paralaxe = {
        mountain : [40, 10, 1]
    };

    var createMountains = function()
    {
        mountainParts = [
            //color, x, y, dir
            {
                l : 0.1,
                s : 0x101010,
                p : [
                    [2, -30, 60, -1],
                    [1, -20, 35, -1],
                    [0, -10, 50, -1],
                    [1, 10, 40, -4],
                    [2, 20, 20, 0],
                    [1, 30, 40, 4],
                    [2, 40, 40, -1],
                    [0, 50, 60, 5],
                    [1, 60, 70, 1],
                    [2, 70, 40, 0],
                    [1, 80, 70, 1],
                    [2, 90, 60, -1]
                ]
            },
            //2
            {
                l : 0.3,
                s : 0x404040,
                p : [
                    [3, -10, 80, -1],
                    [4, 15, 70, -4],
                    [5, 25, 50, 0],
                    [4, 35, 50, 4],
                    [5, 45, 70, -1],
                    [4, 55, 60, 5],
                    [3, 65, 80, 1],
                    [4, 75, 60, 0],
                    [5, 85, 80, 1],
                    [4, 90, 70, -1]
                ]
            },
            //3
            {
                l : 1,
                s : 0x707070,
                p : [
                    [6, -30, 80, 0],
                    [7, -20, 85, -5],
                    [6, -10, 80, 1],
                    [7, 10, 95, -4],
                    [8, 20, 80, 0],
                    [7, 30, 95, 4],
                    [8, 40, 80, -1],
                    [7, 50, 75, 5],
                    [6, 60, 90, 1],
                    [7, 70, 80, 0],
                    [8, 80, 95, 1],
                    [7, 90, 80, -1]
                ]
            }
        ];

        mountains = [
            {
                l : 0,
                p : [
                    -40, 90,
                    -10, 70,
                    5, 80,
                    20, 75,
                    50, 85,
                    90, 87,
                    140, 90,
                    140, 101,
                    -40, 101
                ]
            },{
                l : 1,
                p : [
                    20, 101,
                    60, 70,
                    70, 60,
                    75, 70,
                    83, 60,
                    90, 73,
                    140, 40,
                    140, 101
                ]
            },{
                l : 2,
                p : [
                    -40, 30,
                    10, 40,
                    20, 20,
                    30, 35,
                    40, 40,
                    50, 55,
                    60, 55,
                    70, 50,
                    140, 101,
                    -40, 101
                ]
            }
        ];
    };

    var createMouseListener = function()
    {
        document.addEventListener('mousemove', function(e) {
            mousePos = e.clientX / width;
        });
    };

    var createStars = function()
    {
        stars = [];

        var i = 0;

        for (i = 0; i < starCount; i++) {
            stars.push({
                x : random.nextRealInt(0, width),
                y : random.nextRealInt(0, height / 1.5),
                s : random.nextFloat() * 3
            });
        }

        starColors = [];
        for (i = 0; i < starLayer; i++) {
            starColors.push({
                step    : generateStarColorStep(),
                current : random.nextFloat(),
                target  : random.nextFloat()
            });
        }
    };

    var createRain = function()
    {
        rain = [];

        for (var i = 0, sy; i < rainCount; i++) {

            sy = random.nextRealFloat();

            rain.push({
                x  : getRandomXRainPos(),
                y  : random.nextRealInt(0, sy * height), //abs y pos
                sx : 0, //move x per tick
                sy : sy, //move y per tick
                r  : random.nextRealFloat(), //kp
                ge : random.nextFloat(), //gravity/wind dependency
                v  : random.nextRealFloat() //visibility
            });
        }
    };

    var recreateRainDrops = function(drops)
    {

    };

    var prepareMountains = function()
    {
        for (var i = 0; i < mountainParts.length; i++) {
            mountainParts[i].p.push(
                [
                    Math.max(mountainParts[i].p[mountainParts[i].p.length - 1][0] - 1, 0),
                    140,
                    90,
                    1
                ]
            );
        }
    };

    var setup = function()
    {
        random = new FastRandom();
        canvas = document.getElementById('scene');

        width  = window.innerWidth;
        height = window.innerHeight;

        midWidth  = parseInt(width / 2);
        midHeight = parseInt(height / 2);

        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);

        engine = canvas.getContext('2d');

        createMountains();
        createSunGradient();
        createMouseListener();
        createRain();
        createStars();
        prepareMountains();
        changeWindTarget();
        solveGravityProcc();

        distanceNormalizer = (width + height) / 2;

        if (!engine) {
            return false;
        }

        if (!window.requestAnimationFrame) {
            return false;
        }

        return true;
    };

    var drawBackground = function()
    {
         engine.clearRect(0, 0, width, height);
    };

    var drawSun = function()
    {
        engine.fillStyle = sunGradient;
        engine.fillRect(0, 0, width, height);

        // engine.fillStyle = sunMidGradient;
        // engine.beginPath();
        // engine.arc(midWidth, midHeight, parseInt(width / 10), 0, Math.PI * 2);
        // engine.closePath();
        // engine.fill();
    };

    var solveX = function(percentageX)
    {
        return parseInt(width / 100 * percentageX);
    };

    var solveY = function(percentageY)
    {
        return parseInt(height / 100 * percentageY);
    };

    var drawMountains = function()
    {
        // for (var m = mountains.length - 1, mountain, moveX; m >= 0; m--) {
        //     mountain = mountains[m];
        //     moveX    = solveX(paralaxe.mountain[mountain.l]) * mousePos;
        //
        //     engine.fillStyle = color.mountain[mountain.l];
        //     engine.beginPath();
        //     engine.moveTo(solveX(mountain.p[0]), solveY(mountain.p[1]));
        //
        //     for (var i = 2, lastX, lastY, x, y; i < mountain.p.length; i += 2) {
        //         engine.lineTo(moveX + solveX(mountain.p[i]), solveY(mountain.p[i + 1]));
        //     }
        //
        //     engine.closePath();
        //     engine.fill();
        // }

        // mountainParts = [
        //     //color, x, y, dir
        //     [
        //         [0, -10, 70, 1],
        //         [0, 30, 60, 1]
        //     ]
        // ];
        //

        mountainParts.forEach(function(layer) {

            var moveX       = solveX(40 * layer.l) * (1 - mousePos);
            var bottomUnder = solveY(101);


            //normal and snow
            for(var i = 0; i < 2; i++) {

                var isSnowDrawing = i === 1;

                var x, y, escape, bg, bgSubStr, bottom, bottomX, originY, originOldY;

                var oldBottom  = solveY(101);
                var oldX       = solveX(-40);
                var oldY       = solveY(90);
                var oldEscape  = 0;
                var oldBottomX = solveX(-40);
                var snowY      = 0;

                if (isSnowDrawing) {
                    snowY = height / 30 * visibility.current;
                }

                layer.p.forEach(function(mountain) {

                    bg      = color.mp[mountain[0]];
                    x       = solveX(mountain[1]) + moveX * layer.l;
                    y       = originY = solveY(mountain[2]);
                    bottom  = solveY(101);
                    escape  = solveX(mountain[3]);
                    bottomX = x + escape;

                    if (isSnowDrawing) {
                        bg      = Math.min(0xffffff, bg + layer.s);
                        bottom  = y + 3;
                        y       = y - (height - y) / 30;
                        bottomX = x + 1;

                        if (oldY < y) {
                            y -= height / 20;
                        }
                    }

                    bgSubStr = bg.toString(16);

                    if (bgSubStr.length < 6) {
                        bgSubStr = '0'.repeat(6 - bgSubStr.length) + bgSubStr;
                    }

                    engine.fillStyle = '#' + bgSubStr;


                    engine.beginPath();

                    engine.moveTo(oldX, oldY - snowY);

                    if (isSnowDrawing) {

                        engine.quadraticCurveTo(
                            oldX + (x - oldX) / 2,
                            originOldY + (originY - originOldY) / 2,
                            x + 1,
                            y - snowY
                        );

                    } else {
                        engine.lineTo(x + 1, y - snowY);
                    }

                    engine.lineTo(bottomX + 1, bottom);
                    engine.lineTo(oldBottomX - 1, oldBottom);

                    engine.closePath();
                    engine.fill();



                    oldX       = x;
                    oldY       = y;
                    oldEscape  = escape;
                    oldBottom  = bottom;
                    oldBottomX = bottomX;
                    originOldY = originY;
                });
            }
        });
    };

    var drawDarkness = function()
    {
        engine.fillStyle = 'rgba(0, 0, 0, 0.1)';
        engine.fillRect(0, 0, width, height);
    };

    var getRandomXRainPos = function()
    {
        return random.nextFloat() * width + 1000 * 1000;
    };

    var scaleToGrey = function(scale)
    {
        scale = scale | 0;

        return '#' + (scale + (scale << 8) + (scale << 16)).toString(16);
    };

    var renderRain = function()
    {
        engine.lineWidth   = 2;

        // rain.forEach(function(drops) {
        //     engine.fillRect(drops.x, drops.y, 2, 2);
        // });

        var absX, absBaseX;
        var moveX, moveY;

        var partSize  = parseInt(rain.length / rainParts);
        var colorStep = parseInt((rainColor[0] - rainColor[1]) / rainParts);

        for (var i = 0, baseIndex; i < rainParts; i++) {
            baseIndex = i * partSize;

            engine.beginPath();
            engine.strokeStyle = scaleToGrey(rainColor[0] - colorStep * i);

            for (var d = baseIndex, max = baseIndex + partSize, drops; d < max; d++) {

                drops = rain[d];

                absBaseX = drops.x % width;
                moveY    = (height / 300) + drops.sy * height / 100;
                moveX    = mainWind.current * drops.sy * drops.r;

                gravityPoints.forEach(function(gravPoint) {

                    var distance    = Math.sqrt(Math.pow(gravPoint.x - absBaseX, 2) + Math.pow(gravPoint.y - drops.y, 2));
                    var gravity     = Math.max(0.05, 1 - distance * 2 / distanceNormalizer) * Math.sin(Math.PI / gravPoint.tm * gravPoint.t);
                    // var diverseMove = (gravPoint.y - drops.y) / midHeight;
                    // var absMoveX    = diverseMove * drops.ge * Math.abs((gravPoint.x - absBaseX) / 3 * gravity);
                    var move        = width / 1000 * (gravity + 0.3) * drops.ge;

                    if (gravPoint.d) {
                        drops.sx += move;
                    } else {
                        drops.sx -= move;
                    }

                    moveY += (gravPoint.y - drops.y) / 10 * (gravity / 3);

                    // moveX *= 1 / distanceNormalizer * distance
                    // moveY *= 1 / distanceNormalizer * distance;
                });

                drops.sx *= 0.95;

                var completeMoveX = moveX + drops.sx;
                drops.x += completeMoveX;
                drops.y += moveY;

                if (drops.y > drops.sy * height) {
                    drops.y = random.nextInt(-50, 0);
                    drops.x = getRandomXRainPos();
                }

                if (drops.v > visibility.current) {
                    continue;
                }

                absX = parseInt(drops.x % width);
                engine.moveTo(absX, drops.y | 0);

                // engine.lineTo(absX + 3, drops.y | 0);

                engine.lineTo(
                    parseInt(absX + completeMoveX  * drops.sy),
                    parseInt((drops.y | 0) + 10 * drops.sy + height / 200)
                );
            }

            engine.closePath();
            engine.stroke();
        }
    };

    var changeWindTarget = function()
    {
        mainWind.target = (0.5 - random.nextFloat()) * width / 30;
    };

    var solveWind = function()
    {
        if (random.nextFloat() < 0.01) {
            changeWindTarget();
        }

        if (mainWind.current === mainWind.target) {
            return;
        }

        var diff = mainWind.target - mainWind.current;

        if (Math.abs(diff) < 0.01) {
            mainWind.current = mainWind.target;
            return;
        }

        mainWind.current += diff / 200;
    };

    var drawDebug = function()
    {
        if (debug.length) {
            engine.fillStyle = '#fff';
            engine.font      = '20px Arial';

            var i = 0;

            debug.forEach(function(info) {
                engine.fillText(info, 50, 50 + i++ * 20);
            });

            debug = [];
        }
    };

    var solveGravityProcc = function()
    {
        gravityProcc = random.nextInt(100, 400);
    };

    var solveGravity = function()
    {
        if (tickCounter % gravityProcc === 0) {
            solveGravityProcc();

            var t = random.nextInt(100, 300);

            gravityPoints.push({
                x : random.nextInt(0, width),
                y : random.nextInt(0, height),
                t : t,
                tm : t,
                d : random.nextFloat() < 0.5 ? 0 : 1
            });
        }

        var remove = [];
        for (var i = 0; i < gravityPoints.length; i++) {
            gravityPoints[i].t--;

            if (gravityPoints[i].t === 0) {
                remove.push(i);
            }

            // engine.fillStyle = '#f00';
            // engine.fillRect(gravityPoints[i].x, gravityPoints[i].y, 20, 20);
        }

        for (var r = 0; r < remove.length; r++) {
            gravityPoints.splice(remove[r] - r, 1);
        }
    };

    var generateStarColorStep = function()
    {
        return 0.01 + random.nextFloat() * 0.1;
    };

    var drawStars = function()
    {
        var scale, color, i, starColor, star;

        var stack = parseInt(starCount / starLayer);

        for (i = 0; i < starLayer; i++) {

            scale = parseInt(0xff - starColorDiff * starColors[i].current);
            color = scale + (scale << 8) + (scale << 16);

            engine.beginPath();
            engine.fillStyle = '#' + color.toString(16);

            for (var s = i * stack;  s < stack * (i + 1); s++) {
                star = stars[s];
                engine.moveTo(star.x, star.y);
                engine.arc(star.x, star.y, star.s, 0, Math.PI * 2);
            }

            engine.closePath();
            engine.fill();
        }

        for (i = 0; i < starLayer; i++) {
            starColor = starColors[i];

            if (Math.abs(starColor.target - starColor.current) < starColor.step) {
                starColor.target = random.nextFloat();
                starColor.step   = generateStarColorStep();

            } else if (starColor.target > starColor.current) {
                starColor.current += starColor.step;

            } else {
                starColor.current -= starColor.step;
            }
        }
    };

    var changeVisibility = function()
    {
        visibility.current += (visibility.target - visibility.current) / 100;

        if (tickCounter % 240 === 0) {
            visibility.target = random.nextRealFloat();
        }
    };

    var tick = function()
    {
        var time;

        drawBackground();
        drawSun();
        drawStars();
        drawMountains();
        drawDarkness();


        renderRain();
        solveWind();
        solveGravity();

        drawDebug();
        changeVisibility();
        register();

        tickCounter++;
    };

    var register = function()
    {
        window.requestAnimationFrame(tick);
    };

    this.run = function()
    {
        if (!setup()) {
            return;
        }


        engine.fillStyle = '#000';
        engine.fillRect(0, 0, 100, 100);

        register();
    }
};

var r = new Rain();
r.run();


            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console