Creating Animated Moving Clouds using HTML5

Date: 04th Nov 2011 Author: admin 12 Comments
Posted in: HTML5 |Tags: , , , ,

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 enjoyed this article, feel free to share our tutorial with your friends.
   
   
   

Stay connected with us:

12 Comments

    • Vahagn's Gravatar
    • 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

    • spireas's Gravatar
    • 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 !

    • Goran's Gravatar
    • 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

    • Dustin's Gravatar
    • Im using safari on an 27inch iMac with OSX Lion and all I see in the demo is a tiled image?

    • Roy M J's Gravatar
    • 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.

    • hal's Gravatar
    • 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?

    • Hayk Nahapetyan's Gravatar

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>