Skip to main content

Kiss My App: Collaborating using HTML5 Canvas and WebSockets

The Canvas element introduced in HTML5 is the most talked about feature in HTML5. It allows a developer to draw on a rectangular area and the ability to control each pixel in it. I'm not a very big fan of powerful graphics and animation on the web, however I wanted to try Canvas in conjunction with another popular feature - Web Sockets. The idea is to use the mouse events to draw on the Canvas and then send the coordinates to remote clients using Web Sockets. I have used the pusherapp Web Socket library in my example and this video shows how two clients can play a Tic-Tac-Toe game:

Unable to display content. Adobe Flash is required.


As you can see in this video, the mouse movements made on the canvas will draw lines on it and also cause lines to be drawn on another browser window.



HOW?:
There are various event handlers that can be used with the Canvas element. The one that I have used in this application are the mousedown and the mousemove events. When the user clicks on the Canvas the mousedown event is invoked. The point at the which the mouse was clicked will be marked as the starting point for the line. Now, when one moves the mouse, the mousemove event is invoked. The movement of mouse will then be used to draw the line on the canvas. The next mouse click is then used to mark the end of drawing and any mouse movement will not cause lines to be drawn on the Canvas. This is particularly useful when you want to draw multiple shapes or letters on the Canvas. To start drawing again click anywhere on the Canvas to mark the start point.

In both the cases i.e. on mouseclick and mousemove events, the X and Y coordinates along with the event type is sent over the Web Socket. On receiving the message on the Web Socket, the corresponding action is performed.

Code:

      var canvas, ctx, socket, clicked = true;  
     var oldX = 0, oldY = 0;  
      socket = new Pusher('{api_key}', 'test_channel');  
     /*  
      * Initialize the Canvas   
      * set the line width  
      * and add event listeners - mousedown and mousemove   
      */  
     $(document).ready(function(){  
         canvas = document.getElementById('myCanvas');  
         ctx = canvas.getContext('2d');  
         ctx.lineWidth = "6";  
          canvas.addEventListener('mousedown', drawOnCanvas, false);  
         canvas.addEventListener('mousemove', drawOnCanvas, false);  
     });  
     /*  
      * Function to be invoked when a mousedown or a mousemove event is received  
      */  
     function drawOnCanvas(evt){  
     /*  
      * Post a HTTP request to the server on mousedown and mousemove events.  
      * Post a HTTP request for mousemove only when the mouse is clicked.  
      */  
     if (evt.type == 'mousedown' || !(clicked)) {  
           $.post('send.cfm', {  
                x: evt.x,  
                y: evt.y,  
                eventType: evt.type  
           });  
        }  
     }  
     /*  
      * Bind the socket to an event  
      */  
     socket.bind('test_event', function(data){  
          if (data.eventType == 'mousedown') {  
          /*  
           * Change the start position to the coordinate where the mouse was clicked  
           * Set clicked to false, so that the next mousemove event can send the request to Pusher. See below.  
           */  
          if(clicked) {  
                ctx.moveTo(oldX, oldY);  
                clicked = false;  
          }  
          /*  
           * On second click, stop drawing any more lines on the Canvas until the next mousedown event is received.  
           * This is used to mark an end of a character or a diagram on the Canvas. Allows user to draw multiple characters or diagrams  
           */  
           else {  
                clicked = true;  
           }  
      }  
      /*  
       * In case of a mousemove event draw the line  
       */  
      else if(!clicked){  
           ctx.beginPath();  
           ctx.moveTo(oldX, oldY);  
           ctx.lineTo(data.x, data.y);  
           ctx.stroke();  
           clicked=false;  
      }  
      /*  
       * Update the next start position  
       */  
      oldX = data.x;  
      oldY = data.y;          
 });  
 

The performance of this application depends on the network speed. If you do see the application running slow, you can change the behavior such that the line is drawn if the difference between the new and the old coordinates is greater than some value.

Download code - http://goo.gl/tDDkY

Comments

  1. What is curl? I've signed up to pusherapp, but now the next step is to see "Hello World" using curl.

    ReplyDelete
  2. Are you using ColdFusion to send HTTP request? You can download the code from http://goo.gl/tDDkY. Just replace the api_key, api_secret and api_id in html and cfm file.

    ReplyDelete

Post a Comment

Popular posts from this blog

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code.

What is Minification?

Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript file…

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.