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 ]


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.

                var worker = new Worker("worker.js");
                        document.getElementById("msg").innerHTML = e.data;
            <button onclick="worker.postMessage('msg')">Send message to worker</button>
            <button onclick="worker.postMessage('close')">Close worker</button>
            <div id="msg"></div>

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.

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


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.

            function begin()
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                context.fillStyle = "#000000";
    <body onload="begin()">
        <canvas id="myCanvas" style="border:1px solid black">

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");
                worker[i] = new Worker("ball.js");
                worker[i].postMessage({'cmd': 'draw','msg': ''});
        function draw(e) {
                case 'draw' :
                            context.fillStyle = e.data.msg[2];
                case 'clear' :

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;
                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)});
         case 'close':self.close();
}, false);
function rand(num)
    return Math.round(Math.random()*num);

Sofia _,
Dec 23, 2011, 2:48 AM