![Page 1: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/1.jpg)
LECTURE 2 – MORE CANVAS WITH INPUT AND JAVASCRIPT + WEBSOCKETS AND NODE.JS
Written by Matthew Shelley for Professor Wei Shi
![Page 2: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/2.jpg)
More Canvas with Input
![Page 3: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/3.jpg)
In This Example...
User Input Keyboard Events Mouse (click) events for canvas
Touch events on mobile devices are also included
Game Objects Represented by coloured rectangles, which can be clicked
Canvas Inheritance Render game objects to canvas (only once) Click game objects through canvas based on z-index
![Page 4: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/4.jpg)
Overview of Files
userinput_canvas.htm Very basic page, which serves to include the
necessary JavaScript, CSS, and library files userinput_canvas.css
Disables selecting and dragging of the canvas and any images, due to undesirable behaviour
userinput_canvas.js Creates canvas, draws to it, and handles
clicking of game objects within
![Page 5: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/5.jpg)
Structure of .js File
Constants A few constants are stored atop the .js file
UserInputAndCanvasExample Namespace for the entire demo, which
exposes a single public method, init()
$(document).ready(function() {...}); Called when the document has finished
loading
![Page 6: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/6.jpg)
UserInputAndCanvasExample
m_keydownFunc [variable / function] Takes in a ‘key code’ for the key just pressed
BaseCanvas [class] Basic canvas object, which references a jQuery
canvas element to respond to clicks and touches GameObject [class]
A simple object, which can be rendered and clicked GameWorld [class]
Extends BaseCanvas to manage and render objects m_gameWorld [variable / object]
Reference to a GameWorld object
![Page 7: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/7.jpg)
User Input
m_keydownFunc(e) Assigned to the document body through
init() Uses a switch statement to handle each
key press e.which returns the key code
For key values, see: http://www.cambiaresearch.com/articles/
15/javascript-char-codes-key-codes
![Page 8: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/8.jpg)
User Input
Each canvas object has a virtual function to handle click and touch events: canvasElementClickOrTouchCallback(e) Assigned in the constructor for each
canvas
To fetch the relative position of a click or touch within a canvas, pass along e to: getClickOrTouchPosition(e)
![Page 9: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/9.jpg)
Game Objects
Represent a coloured rectangle, which can be drawn and clicked on through the canvas
isPointInside(point) Checks if a point exists within a given
area
handleClick() [virtual] Response for a click
![Page 10: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/10.jpg)
Canvas
BaseCanvas Creates a canvas element, which is wrapped
by jQuery, and assigns the click callback Assign ‘self’ reference to DOM element Click method simply avoids ‘bubble up’
Note: this method treats ‘this’ as the DOM element
Disables dragging and selecting through DOM methods; supposedly jQuery has problems
Does not have a render() method, as there is nothing for an empty canvas to render
![Page 11: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/11.jpg)
Canvas
GameWorld Extends BaseCanvas to handle GameObject
creation, clicking, and drawing When clicked, the object with the highest
zIndex that contains the ‘target’ has its handleClick() method called
createGameObject Creates a game object and then stores it in
an array based on its zIndex renderOneFrame
Draws all game objects exactly once
![Page 12: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/12.jpg)
Useful Links
Most of the code from the example: http://www.ibm.com/developerworks/we
b/library/wa-games/index.html jQuery:
http://jquery.com/ Class:
http://ejohn.org/blog/simple-javascript-inheritance/
jCanvas: http://calebevans.me/projects/jcanvas/in
dex.php
![Page 13: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/13.jpg)
More JavaScript
![Page 14: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/14.jpg)
JavaScript Object Notation Variables in JavaScript are dynamically-typed
A variable can be a string, then an integer, then an array, then a function, then an object, etc.
Objects are also dynamic, as new properties can be added or deleted as necessary Properties are just variables, too! Similarly, they are
dynamic and can be objects as well.
Objects can be seen as ‘associative arrays’ or ‘dictionaries’; they assign values to properties
![Page 15: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/15.jpg)
JavaScript Object Notation An ‘empty’ object can be created like so:
var x = {}; // an empty associative array
An object can have some initial properties: var x ={a: 1, b: 2}; var y = {‘a’: 29, “b”: 3}; var z = {a: 18, “b” 33}; Any of these formats is valid Any string can be used with no limit on length
![Page 16: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/16.jpg)
JavaScript Object Notation To read a property:
x.a x[‘a’] x[“a”]
To set a property: x.a = 7; x[‘a’] = 17; x[“a”] = 81;
![Page 17: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/17.jpg)
JavaScript Object Notation To create a property:
Simply set its value as though it already existed
To delete a property: delete x.a; delete x[‘b’]; delete x[“c”]
To check if a property exists: (a in x) OR (‘b’ in y) OR (“c” in z)
You cannot do “not in” or “!in” or some variant x.hasOwnProperty(‘a’) OR y.hasOwnProperty(“b”)
You can do !x.hasOwnProperty(...)
![Page 18: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/18.jpg)
JavaScript Object Notation To traverse each property:
for (key in obj) // this is a for-each loop{if (obj.hasOwnProperty(key))obj[key].doSomething();
}
No assumptions can be made on key ordering
We refer to this entire notation as JSON
![Page 19: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/19.jpg)
Common jQuery
jQuery is an additional library for JavaScript that is commonly used in client-side applications
The primary $(...) method is complex As per the name jQuery, it queries the document for
DOM elements, which meet certain criteria, and then returns their ‘jQuery-wrapped’ versions
$(“body”) returns the body element, for instance $(“img”) returns every img tag
jQuery simplifies the majority of traditional DOM-manipulation methods
![Page 20: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/20.jpg)
Common jQuery
To create an element: jqElement = $(document.createElement("canvas")) ; jqElement = $(“<canvas>”); // create raw HTML jqElement = $(“<canvas></canvas>”);
To add an element to another: jqElement.append(objectToAdd); $(“body”).append(“<canvas>”); // append raw HTML
To remove an element: jqElement.remove(); // also removes any children
![Page 21: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/21.jpg)
Common jQuery
To set an attribute of a jQuery element: jqElement.attr(“attr”, “value”);
Note that if the selector retrieves more than 1 element all of those element will be updated! $(“img”).attr(“width”, 320); // all image widths
change
To append callbacks: jqElement.on(“click”, someFunc); jqElement.click(function() {...});
![Page 22: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/22.jpg)
BREAK
![Page 23: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/23.jpg)
WebSockets
![Page 24: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/24.jpg)
WebSockets
WebSockets work similar to sockets, but instead they specifically communicate between a web browser and a web server Messages are sent and received between the two
The protocols ws:// and wss:// are built atop of http:// and https://, respectively Ports 80 and 443 are similarly used
WebSockets require both server and client support So, you might need a virtual private server
![Page 25: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/25.jpg)
WebSockets – Echo Example
Launch the websocket-echo.htm example A connection is made with the server
ws://echo.websocket.org/ A message is sent to the server The same message is received Both messages are displayed for
comparison Afterward, the client disconnects
![Page 26: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/26.jpg)
Useful Links
About WebSockets: http://www.websocket.org/aboutwebsock
et.html
Websocket Echo Example: http://www.websocket.org/echo.html
![Page 27: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/27.jpg)
Node.js
![Page 28: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/28.jpg)
Software Installation
First, please download and install node.js http://nodejs.org/ Click ‘Install’ or go to the ‘Downloads’
page Once downloaded, run the installer
Second, please download PuTTY http://www.chiark.greenend.org.uk/~sgt
atham/putty/download.html
![Page 29: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/29.jpg)
Introduction to Node.js
“Node.js is a platform built on Chrome's JavaScript runtime for
easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time
applications that run across distributed devices.”
- nodejs.org
![Page 30: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/30.jpg)
Using Node.js
With command prompt, navigate to the folder containing your code Use the cd command on Windows
To run a file named ‘example.js’: node example.js
Server-side JavaScript code We are not writing code for a web browser, but
rather code that will be handled by the server
![Page 31: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/31.jpg)
Node.js – Example 1
The first example displays “hello,” and then “world” 2 seconds later to command prompt
![Page 32: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/32.jpg)
Node.js – Example 2
We create an http server, which listens to requests on port 8000 and responds to all incoming connections similar to before
First, run the example via Command Prompt
Then, connect to localhost:8000 via PuTTY
“Hello” followed by “world” 2 seconds later should appear in PuTTY’s console
![Page 33: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/33.jpg)
Node.js – Example 3
This example creates a TCP ‘echo’ server that simply sends back each message that the server receives
Like before, load the example in command prompt and then connect to localhost:8000 through PuTTY
Type a message in PuTTY to see it returned
![Page 34: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/34.jpg)
Node.js – Example 4
The final example creates a simple chat room where multiple users can write and messages, which are then broadcast to everyone else
This example demonstrates how to store multiple connections; filter out who receives what messages; and, handle clients that disconnect
Multiple PuTTY clients are necessary
![Page 35: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/35.jpg)
Socket.IO
Socket.IO builds on top of node.js to improve network connectivity on many devices, while providing some ‘interface’ improvements
http://socket.io/
To install socket.io, use command prompt (assuming node.js has been installed): npm install socket.io
![Page 36: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/36.jpg)
Socket.IO - Example
Run “node socketio-example.js” via command prompt, like usual
Launch “socketio-example.htm” in a web browser, preferably Google Chrome
Using developer tools, it is possible to see messages logged to the console These messages contain messages received
by the client that were sent by the server
![Page 37: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/37.jpg)
Disclaimer
Unless you have a Virtual Private Server or a host that supports websockets, node.js or some variant, you will not be able to use any of these services outside of your computer
As an alternative, one can use AJAX to call server-side code, such as PHP We will look into AJAX in the next lecture
![Page 38: Lecture 2 – More Canvas with input and JavaScript + WebSockets and node.js](https://reader035.vdocuments.net/reader035/viewer/2022062501/56816193550346895dd133da/html5/thumbnails/38.jpg)
Useful Links
node.js http://www.nodejs.org/
“Introduction to Node.js with Ryan Dahl” http://www.youtube.com/watch?v=jo_B4LTHi
3I “How do I get started with node.js?”
http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js
“Advanced HTML5 JavaScript: Down 'n Dirty” http://www.youtube.com/watch?v=Pm6Ch4
qoNe8&feature=relmfu