The HTML5 Canvas element opens up a whole new world in regards to what can be done in the browser especially for things like multi-player games. I’ve taken a couple of my previous articles: here and here and combined them into the basis of what could be used for any application or game that needs real-time communications. To make it fun I’ve added the HTML5 Canvas into the mix. Simply connect and click on a free spot within the canvas and a randomly colored square will get drawn on yours and every other connected user’s screen as well.
Note: I’ve tested this on the latest Firefox (on Windows), IE9, latest Safari (on OS X), latest Chrome (on Windows and OS X), iPad (2), and Android 2.2 (Droid X).
I’ve used Touchable to make it easier to detect clicks/taps on the HTML5 Canvas element so whether the user is on a mobile device like an iPad or a desktop browser like Firefox it will detect the location of the click/tap and process it automatically for me therefor I need not worry about what device they are using. The code also uses JQuery 1.6.1.
The interface is simple, I draw a canvas element on the screen outlined in green to make it obvious and then have a small status span as well as buttons to connect or disconnect.
Here is the full code listing:
Note: I only added code to set the squares at their specified coordinates, I didn’t set the color property so the square’s colors would be the same on all browsers, you can easily pass the square’s color in the message if you want to do that. I’m using the simplest possible way to pass the square’s coordinates as well – through the room chat channel via CHAT_MESSAGE. Check out this article for ideas to pass messages.
You can try a live demo here. If you have trouble with the online demo I’ve noticed sometimes the tryunion.com server can be a bit slow (it’s just for testing) so you might want to just try everything out on localhost.