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

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

Server sent events with HTML5 and ColdFusion

There are several ways to interact with the server apart from the traditional request\response and refresh all protocol. They are polling, long polling, Ajax and Websockets ( pusherapp ). Of all these Ajax and Websockets have been very popular. There is another way to interact with the server such that the server can send notifications to the client using Server Sent Events (SSE) . SSE is a part of HTML5 spec:  http://dev.w3.org/html5/eventsource/

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.