Written by Matthew Shelley for Professor Wei Shi LECTURE 2 – MORE CANVAS WITH INPUT AND JAVASCRIPT + WEBSOCKETS AND NODE.JS More Canvas with Input 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 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 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 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 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/javas cript-char-codes-key-codes 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) 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 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 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 Useful Links Most of the code from the example: http://www.ibm.com/developerworks/web/library/ wa-games/index.html jQuery: http://jquery.com/ Class: http://ejohn.org/blog/simple-javascript- inheritance/ jCanvas: http://calebevans.me/projects/jcanvas/index.php More JavaScript 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 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 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; 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(...) 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 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 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 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() {...}); BREAK WebSockets 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 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 Useful Links About WebSockets: http://www.websocket.org/aboutwebsocket.html Websocket Echo Example: http://www.websocket.org/echo.html Node.js 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/~sgtatham/pu tty/download.html 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 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 Node.js – Example 1 The first example displays “hello,” and then “world” 2 seconds later to command prompt 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 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 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 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 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 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 Useful Links node.js http://www.nodejs.org/ “Introduction to Node.js with Ryan Dahl” http://www.youtube.com/watch?v=jo_B4LTHi3I “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=Pm6Ch4qoNe 8&feature=relmfu