Creating Animated Moving Clouds using HTML5

HTML5 clouds

HTML5 clouds

Today I have prepared you something really entertaining. Of course, we implement it with our favorite html5. This work will show you how to create a beautiful flying clouds across the sky. In the implementation, I decided to use an additional library: https://github.com/mrdoob/three.js

Here are our demo and downloadable package:

Live Demo
download in package

Ok, download the source files and lets start coding !


Step 1. HTML

Here are html code of our clouds page

index.html

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>HTML5 clouds | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
        <script src="js/ThreeWebGL.js"></script>
        <script src="js/ThreeExtras.js"></script>
    </head>
    <body>
        <script id="vs" type="x-shader/x-vertex">
            varying vec2 vUv;
            void main() {
                vUv = uv;
                gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
            }
        </script>
        <script id="fs" type="x-shader/x-fragment">
            uniform sampler2D map;
            uniform vec3 fogColor;
            uniform float fogNear;
            uniform float fogFar;
            varying vec2 vUv;
            void main() {
                float depth = gl_FragCoord.z / gl_FragCoord.w;
                float fogFactor = smoothstep( fogNear, fogFar, depth );
                gl_FragColor = texture2D( map, vUv );
                gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 );
                gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );
            }
        </script>

        <div class="container">
            <canvas id="panel" width="10" height="1"></canvas>
        </div>
        <script type="text/javascript" src="js/script.js"></script>
        <footer>
            <h2>HTML5 clouds</h2>
            <a href="http://www.script-tutorials.com/html5-clouds/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </footer>
    </body>
</html>

Step 2. CSS

Here are used CSS styles

css/main.css

*{
    margin:0;
    padding:0;
}
body {
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    background-image: url(../images/sky.jpg);
}
footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}
footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

Step 3. JS

js/ThreeWebGL.js and js/ThreeExtras.js

This is our new service libraries (available in package)

js/script.js

// inner variables
var canvas, ctx;
var camera, scene, renderer, meshMaterial, mesh, geometry, i;
var mouseX = 0, mouseY = 0;
var startTime = new Date().getTime();
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

if (window.attachEvent) {
    window.attachEvent('onload', main_init);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function() {
            curronload();
            main_init();
        };
        window.onload = newonload;
    } else {
        window.onload = main_init;
    }
}

function main_init() {

    // creating canvas and context objects
    canvas = document.getElementById('panel');
    var ctx = canvas.getContext('2d');

    // preparing camera
    camera = new THREE.Camera(30, window.innerWidth / window.innerHeight, 1, 5000);
    camera.position.z = 6000;

    // preparing scene
    scene = new THREE.Scene();

    // preparing geometry
    geometry = new THREE.Geometry();

    // loading texture
    var texture = THREE.ImageUtils.loadTexture('images/clouds.png');
    texture.magFilter = THREE.LinearMipMapLinearFilter;
    texture.minFilter = THREE.LinearMipMapLinearFilter;

    // preparing fog
    var fog = new THREE.Fog(0x251d32, - 100, 5000);

    // preparing material
    meshMaterial = new THREE.MeshShaderMaterial({
        uniforms: {
            'map': {type: 't', value:2, texture: texture},
            'fogColor' : {type: 'c', value: fog.color},
            'fogNear' : {type: 'f', value: fog.near},
            'fogFar' : {type: 'f', value: fog.far},

        },
        vertexShader: document.getElementById('vs').textContent,
        fragmentShader: document.getElementById('fs').textContent,
        depthTest: false
    });

    // preparing planeMesh
    var planeMesh = new THREE.Mesh(new THREE.PlaneGeometry(64, 64));
    for (i = 0; i < 10000; i++) {
        planeMesh.position.x = Math.random() * 1000 - 500;
        planeMesh.position.y = - Math.random() * Math.random() * 200 - 15;
        planeMesh.position.z = i;
        planeMesh.rotation.z = Math.random() * Math.PI;
        planeMesh.scale.x = planeMesh.scale.y = Math.random() * Math.random() * 1.5 + 0.5;

        THREE.GeometryUtils.merge(geometry, planeMesh);
    }

    mesh = new THREE.Mesh(geometry, meshMaterial);
    scene.addObject(mesh);

    mesh = new THREE.Mesh(geometry, meshMaterial);
    mesh.position.z = - 10000;
    scene.addObject(mesh);

    // preparing new renderer and drawing it
    renderer = new THREE.WebGLRenderer({ antialias: false });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    // change positions by mouse
    document.addEventListener('mousemove', onMousemove, false);

    // change canvas size on resize
    window.addEventListener('resize', onResize, false);

    setInterval(drawScene, 30); // loop drawScene
}

function onMousemove(event) {
    mouseX = (event.clientX - windowHalfX) * 0.3;
    mouseY = (event.clientY - windowHalfY) * 0.2;
}

function onResize(event) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

function drawScene() {
    position = ((new Date().getTime() - startTime) * 0.1) % 10000;

    camera.position.x += mouseX * 0.01;
    camera.position.y += - mouseY * 0.01;
    camera.position.z = - position + 10000;

    renderer.render(scene, camera);
}

Most of code will pretty easy for understanding – I have tried to comment this code as possible.


Live Demo
download in package

Enjoyed this Post?

If you enjoy our articles, feel free to share our tutorials with your friends.

50 thoughts on “Creating Animated Moving Clouds using HTML5

  1. Thanks for the articles, they are really great ))

    P.S. I think in your 6th article you`ll be so tired, that you will publish just JS lool

  2. Grate work. This is what i am looking for.
    I am new in html5 and javascript and i have a problem.
    When i move the mouse ,left for example, the clouds did not stop moving left.
    How i will stop the movement of clouds??

    Thanks !

    • Hello spireas,
      Normal functional is:
      when you move your mouse to left – clouds move to right.
      When you move mouse to right – clouds move to left.
      If mouse Up – clouds – down, and back.
      Clouds not should flu to left of you move your mouse to left. And yes, clouds have own width, so if you would like to limit its move range, try to do it in ‘onMousemove’ function as example.

  3. Just found out that its WebGL – 3D Canvas graphics thats not supported… anyway seems things are moving fast forward so i guess soon we will have support for 3D from all major browsers

    • Tiled?
      Interesting, can you make screenshot and sent it to my email (aramisgc@gmail.com)? I want to see how it looks at 27″

  4. This is simply great Aramis. But one question is even though everyone saying this is html5, but this works with javascript coding right..??.. Using canvas as a frame we write code. Is there any specific tutorial or so where i can learn the scripting for animations or is this purely javascript. Apologise my knowledge in this as i am only a novice in web development.

  5. Hi, This is very impressive, just a couple of issues though. Can you confirm how I can get this working on IE/Chrome/Safari please? The only browser it seems to work on is firefox. Does this need a fix for the other berowsers?

  6. Hi Hal,

    Yes, It works well in Chrome (and as I suspect – in Safari too, because as I know – Safari and Chrome have common core). Yes, demo can not work in IE (because of ThreeWebGL.js library)

    • Hi Candya,
      Can you describe your problem? Because it works in the same way in both browsers (I’ve just checked it)

  7. Hi,

    first of all: great work! It was exactly what I was searching for. Actually I wanted to integrate a further animation which depends on the current release of three.js (r54). I am running into problems to get the clouds working with this new version. I changed some things (*) accordingly the change log of three.js but had no success with it. Do you have already made some expierences with migrating this sample to the newer/newest version or migrating other code parts ?

    * I changed “MeshShaderMaterial” to “ShaderMaterial” and tried to set a 90° rotation to the plane since PlaneGeometry changed from vertical orientation to horizontal orientation.

    • Hello JFM,
      No, I haven’t played with the latest version of three.js. But I suppose that they changed something in their sources. I’d like to see which result you have now (please contact with my using form in the bottom of website) – and maybe I will be able to help you.

    • Thank You Tony for your comment,
      Can you please explain which dark clouds you mentioned? Basically, there is the background image and flying clouds. The most far clouds – darkest.

  8. This example is absolutely beautiful and I’d love to use this with slightly different backgrounds.
    Is there a way of fading to black the whole window after 30 seconds and it automatically stops and goes back to the previous link?
    I am a beginner and start glazing over after the minmum of tech speak…..:)

    regards

    dennis

  9. IMPRESSIVE! Really nice work, well done.

    i just played a bit with the code and couldn’t figure it out if it is possible to wrap the animation in a div or section or something else to have other things around. For example to use the animated clouds only in the Header…

    Could you give me a hint or isn’t it possible?

    • Hello Marius,
      Yes, this is possible. The one of ways is to use the canvas element with certain sizes

  10. Hi,

    I downloaded this source and tested it on my localhost.
    I’m having trouble to show the clouds animation on the I want.
    Now it showing on the last section and below of my testing site.
    I have 5 in my html5 site. I want it to show it on my 1st .
    Now the issue is, it’s showing on the last and below.

    Is there any way to solve?

    • Actually, clouds is the canvas element (which is similar as usual DIV element). It means, that if you need to move it over your page, you can use the same styles as you usually use for DIV elements.
      You can change its ‘position’ property, and maybe even z-indexes

    • Hi shanaka, I already answered the same question to Pan, please read the comments above.
      The reason is that your browser hasn’t finished loading of resource images yet.

  11. Thank you for the script. :)
    Is there any library that works on all browsers? If not, I will try to make a snapshot and stop script working when the browser is IE or Chrome. :(

  12. I really love this html5 animation but for some reason it is not working in my chrome browser.
    After I downloaded and extracted the package, I opened it straight in chrome and got this:

    http://postimg.org/image/jn5hkhh5d/

    Please take a look! It seems to work fine in firefox but it want it to work is chrome as well!
    How can I solve it??

    Keep up the great animations!

      • Hello,

        It doesn’t seem to load even after 30s. The live demo from this page works straight away in chrome but the downloaded source version doesn’t.

      • Hi Atta,
        It should, there is one thing which you should know: the black area is not loaded pictures (of clouds). Make sure that both images are accessible in your browser (‘images’ folder)

      • Having the same issue as Atta. I waited for several minutes and sadly the clouds never showed in Safari. Works really well in firefox.

  13. Hi Andrew,
    Very nice and superb work. Unfortunately you can’t find the answer to the question some dudes have done before.
    Question: “how can i remove or disable the dark cloud?”
    Answer :Basically, there is the background image and flying clouds. The most far clouds – darkest.

    The thing is that the black “far clouds” appears through the white clouds so it f* up the beautiful mood .
    This issue also appears on your demo after a while.

    Is it possible to fix this by changes in your code?

    • Hi Bobic,
      Yes, it is possible to:
      a) change fog color:
      var fog = new THREE.Fog(0xFFFFFF, – 100, 5000);
      b) push it further:
      var fog = new THREE.Fog(0x251d32, – 100, 50000);

  14. I noticed a depth problem. After a while when recreate the new clouds they appear in front of the old clouds,
    Did you find a solution to this.. i am still looking where the depth counter is

Leave a Reply

Your email address will not be published. Required fields are marked *

*

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>