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

How to use the APP_INITIALIZER token to hook into the Angular bootstrap process

I've been building applications using Angular as a framework of choice for more than a year and this post is not about another React vs Angular or the quirks of each framework. Honestly, I like Angular and every day I discover something new which makes development easier and makes me look like a guy who built something very complex in a matter of hours which would've taken a long time to put the correct architecture in place if I had chosen a different framework. The first thing that I learned in Angular is the use of the APP_INITIALIZER token.

Using MobX to manage application state in a React application

I have been writing applications using React and Redux for quite some time now and thought of trying other state management solutions out there. It's not that I have faced any issues with Redux; however, I wanted to explore other approaches to state management. I recently came across MobX  and thought of giving it a try. The library uses the premise of  `Observables` to tie the application state with the view layer (React). It's also an implementation of the Flux pattern wherein it uses multiple stores to save the application state; each store referring to a particular entity. Redux, on the other hand, uses a single store with top-level state variables referring to various entities.

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 f...