Tutorials‎ > ‎

Bouncing Ball using Canvas and Worker HTML 5

posted Dec 23, 2011, 2:33 AM by Sofia _   [ updated Aug 15, 2016, 11:26 PM by Surya Wang ]

HTML5

What is HTML5? HTML5 is a language for structuring and presenting content for the World Wide Web, a core technology of the Internet. It is the latest revision of the HTML standard. There is a lot of new features in HTML5. Why we use HTML5? Because there’s many new features and which is very powerful and easy to learn. In here, we are going to learn about worker and canvas in HTML5.

Web Worker

The Web Workers specification defines an API for spawning background scripts in your web application. Web Workers allow you to do things like fire up long-running scripts to handle computationally intensive tasks, but without blocking the UI or other scripts to handle user interactions.

Normally, we write worker = new Worker("myscript.js") and use postMessage to transfer information between myscript.js and our html page. In "myscript.js" we a event handler to define what we are going to do if receive a message and we can use postMessage send a message to our HTML page. In our html page, we have a event handler just like in "myscript.js" to define what we are going to do if receive a message.

There's a simple example about it. This is the html page. First, we need two button and one div to show the message. When the button is click, the worker will post message and it will be handle at "worker.js". At the script in the html page, don't forget to declare the worker and addEventListener to handle the event if the worker post message.

<html>
        <body>
            <script>
                var worker = new Worker("worker.js");
                worker.addEventListener("message",function(e){
                        document.getElementById("msg").innerHTML = e.data;
                },false);
            </script>
            <button onclick="worker.postMessage('msg')">Send message to worker</button>
            <button onclick="worker.postMessage('close')">Close worker</button>
            <div id="msg"></div>
        </body>
</html>

This is the "worker.js". In here, we handle the message event. If the data we receive is msg then we will postMessage to the html page that the message has been received. If the data is close, the worker will be closed.

self.addEventListener("message",function(e){
    if(e.data == "msg")self.postMessage("The message receive");
    else if(e.data == "close"){
        self.close();
        self.postMessage("I have been closed");
    }
},false);

Canvas

The canvas is the html5 element uses javascript to draw graphics in web page. With html5, we are free to draw anything we want and control the animation in the canvas area. How to begin? Just add <canvas> </canvas> in your body and begin draw with javascript.

This is a simple example to draw circle using canvas in HTML5. We need to get the canvas element and getContext from canvas. After that we begin to draw using context. Fillstyle to arrange the fill style, beginpath to begin. After that, use arc, with arc we can draw circle, half circle and ext. context.arc(x,y,radius,startAngle,endAngle, clockwise); we can adjust what we want to draw by change the parameter in arc. Last we need to call closePath and fill.


<html>
    <head>
        <script>
            function begin()
            {
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                context.fillStyle = "#000000";
                context.beginPath();
                context.arc(20,20,10,0,Math.PI*2,false);
                context.closePath();
                context.fill();
            }
        </script>
    </head>
    <body onload="begin()">
        <canvas id="myCanvas" style="border:1px solid black">
        </canvas>
    </body>
</html>

Canvas and Worker

In this demo, i am using canvas and worker in HTML 5 to make multiple bouncing ball. Each of the worker will handle one ball. First of all, don’t forget to add the canvas area in your web. The canvas’s id is “myCanvas”. Let’s begin to the javascript part.

I have a begin function that called when the page is ready. In this function i am declare worker using looping. Each of the worker call postMessage and add event listener to it. In postMessage, we declare what we want to send. In addEventListener, we use draw as the function that call when a message is sent from worker.

In the draw function, we handle the message that is sent. If the 'cmd' is draw, we will draw circle according the information that sent and if the 'cmd' is clear, we are goint to clear pixel according the information that sent.


var worker = new Array();
        var speed = 5;
        var flag = new Array();
        var i,j;
        var canvas;
        var context;
        var total = 5;
 
        function begin()
        {
            canvas = document.getElementById("myCanvas");
            context = canvas.getContext("2d");
            for(i=0;i<total;i++)
            {
                worker[i] = new Worker("ball.js");
                worker[i].postMessage({'cmd': 'draw','msg': ''});
                worker[i].addEventListener('message',draw,false);
            }
        }
 
        function draw(e) {
            switch(e.data.cmd)
            {
                case 'draw' :
                            context.fillStyle = e.data.msg[2];
                            context.beginPath();
                            context.arc(e.data.msg[0],e.data.msg[1],10,0,Math.PI*2,true);
                            context.closePath();
                            context.fill();
                            break;
                case 'clear' :
                            context.clearRect(e.data.msg[0],e.data.msg[1],20,20);
                            break;
            }
        }

In ball.js, we have a function to handle the postMessage. In the function, i arrange the position of my ball and let it loop using setInterval. The position is according to the current position and how the ball will bounce. I am using random to manage the color of the ball. After arrange the position and color, we use postMessage to send message to our html page to draw the ball. Remember, each time before draw the ball, we need to erase the ball first.


self.addEventListener('message', function(e) {
    var data = e.data;
    var x,y,ax,ay;
    var ballSize = 10;
    var canvasW = 500;
    var canvasH = 300;
    var speed = 5;
    var bX,bY;
 
    switch (data.cmd) {
        case 'draw':
            x = rand(canvasW);
            y = rand(canvasH);
            ax = ay = speed;
            setInterval(function()
            {
                bX = x - ballSize/2;
                bY = y - ballSize/2;
                self.postMessage({'cmd':'clear', 'msg': new Array(bX,bY)});
                var color = "rgb("+rand(255)+","+rand(255)+","+rand(255)+")";
                if(x + ballSize > canvasW || x < 0)ax *= -1;
                if(y + ballSize > canvasH || y < 0)ay *= -1;
                x += ax;
                y += ay;
                self.postMessage({'cmd':'draw', 'msg': new Array(x+ballSize/2,y+ballSize/2,color)});
            },50);
            break;
         case 'close':self.close();
            break;
    };
}, false);
 
function rand(num)
{
    return Math.round(Math.random()*num);
}


ċ
ball+worker.zip
(1k)
Sofia _,
Dec 23, 2011, 2:48 AM