Creating real-time games and web apps with the HTML5 Canvas, JQuery and the Union Platform

Post to Twitter

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

To get this project working you need to install Union. See my previous article on how to do that as well as download links. You will also need a copy of the Touchable JQuery plugin.

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:

<!DOCTYPE html>
<html lang="en">
    <head>
    <title>Realtime Canvas</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
	<script type="text/javascript" src="OrbiterMicro_1.0.0.370_Release_min.js"></script>
	<script type="text/javascript" src="touchable.min.js"></script>
	<script>
	$(function() {
		var canvasContext;
		var orbiter;
		var UPC;
		var msgManager;
		var roomID = 'CanvasRoom';
		
		orbiter = new net.user1.orbiter.Orbiter();
		msgManager = orbiter.getMessageManager();
		UPC = net.user1.orbiter.UPC;
		$touchableCanvas=$('#mainCanvas').Touchable();
		
		$('#btnConnect').hide();
		$('#btnDisconnect').hide(); 
		
		if(!orbiter.getSystem().isJavaScriptCompatible()) {
			displayChatMessage("Your browser is not supported.");
		}
		else {
			$('#btnConnect').show();
		}
		
		$(orbiter).bind(net.user1.orbiter.OrbiterEvent.READY, readyListener);
		$(orbiter).bind(net.user1.orbiter.OrbiterEvent.CLOSE, closeListener);

		msgManager.addMessageListener(UPC.JOINED_ROOM, joinedRoomListener, this);
		msgManager.addMessageListener(UPC.CLIENT_ADDED_TO_ROOM, clientAddedListener, this);
		msgManager.addMessageListener(UPC.CLIENT_REMOVED_FROM_ROOM, clientRemovedListener, this);
		msgManager.addMessageListener("CHAT_MESSAGE", chatMessageListener, this, [roomID]);			

		canvasContext = $('#mainCanvas').get(0).getContext('2d'); 

		function readyListener(e) {
			$('#connectionStatus').css('background-color', '#ff0');
			$('#connectionStatus').text('Wait...');
			$('#btnConnect').hide();
			$('#btnDisconnect').show();
			
			// Create a chat room
			msgManager.sendUPC(UPC.CREATE_ROOM, roomID);
			// Join the chat room
			msgManager.sendUPC(UPC.JOIN_ROOM, roomID);
		}

		function closeListener(e) {
			$('#connectionStatus').css('background-color', '#f00');
			$('#connectionStatus').text('Disconnected');
			$('#btnConnect').hide();
			$('#btnDisconnect').hide(); 				
		}

		function joinedRoomListener() {
			$('#connectionStatus').css('background-color', '#0f0');
			$('#connectionStatus').text('Ready');
		}

		function clientAddedListener(roomID, clientID) {
		  // Someone joined the room
		}

		function clientRemovedListener(roomID, clientID) {
		  // Someone left the room
		}

		function chatMessageListener(fromClientID, message) {				
			var msgCoords = message.split('~');
			canvasContext.fillStyle = getRandomColor();
			canvasContext.fillRect(msgCoords[0] - 25, msgCoords[1] - 25, 50, 50);
		}
		
		$touchableCanvas.click(function(e, touch){
			if(touch == undefined)
				return;
			// Send a message to other connected users showing the new square
			msgManager.sendUPC(UPC.SEND_MESSAGE_TO_ROOMS, "CHAT_MESSAGE", roomID, "true", "", touch.startTouch.x + "~" + touch.startTouch.y);				
		});			
		
		$('#btnDisconnect').click(function() {
			orbiter.disconnect();
		});
		
		$('#btnConnect').click(function() {
			orbiter.connect("tryunion.com", 80);
			//orbiter.connect("localhost", 9100);
		});
		
		function getRandomColor() {
		  function c() {
			return Math.floor(Math.random()*256).toString(16)
		  }
		  return "#"+c()+c()+c();
		}
	});
	</script>
	<style>
      #mainCanvas
      {
        background-color: #000;
        border: solid 2px #0F0;
      }
      body
      {
        background: #000;
      }
     </style>
    </head>
 
    <body>
	    <canvas id="mainCanvas" width="400" height="400">Canvas is not supported</canvas>
		<div>
            <span id="connectionStatus" style="background-color: #f00; padding: 3px 3px 3px 3px;">Disconnected</span>
            <input type="button" id="btnConnect" value="Connect" />&nbsp;
            <input type="button" id="btnDisconnect" value="Disconnect" />
        </div>
    </body>
</html>

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.

Post to Twitter

This entry was posted in Android, HTML5, JavaScript, Mobile, Online Games, Union Framework. Bookmark the permalink.

2 Responses to Creating real-time games and web apps with the HTML5 Canvas, JQuery and the Union Platform

  1. Pingback: HTML5 Blog on: Creating a real-time games or web apps with HTML5 Canvas, JQuery and the Union Platform | MiloRiano: Computers news, tips, guides...

  2. xml_2009 says:

    Hello, it’s good tutorial.. thanks
    I have a question :
    – If the number of visitors to a very large(E.G : 1000visitors)… the pressure on the server will be high.

    I want to explain this part in One or TWO lines

    Thank you for this big tuto.

Comments are closed.