Geek Meet - Creating Games with HTML5 and JavaScript


Published on

In this talk I will give you an overview of the new role that browsers are adopting to support games and the technologies and processes that are helping that happen. This includes areas like 2D graphics with canvas, console-like 3D games with WebGL, gamepad support, immersive full-screen experiences, multiplayer games with WebSockets, and much more.

Geek Meet - Creating Games with HTML5 and JavaScript

  1. 1. E S M ipt A Scr G G va T IN d Ja es EA ML5 a n bH aw k CR HT Ro ith WHi, I’m Rob Hawkes and I’m here today to talk about the technologies behind HTML5 andJavaScript games.
  2. 2. I work at Mozilla, a non-profit fighting for a better Web. The same guys who make Firefox.I’m pretty fond of Mozilla. So much so that my girlfriend made me a chicken and leek pie withextra Firefox goodness.It was delicious.
  3. 3. Before we move on I just have a quick disclaimer.This whole talk is about HTML5 and JavaScript as technologies used in the creation of games.They’re technologies that are intrinsically linked to each other by nature, but saying HTML5and JavaScript every single time makes my head hurt.So instead I’ll just be saying HTML5.Just bear in mind that whenever I mention HTML5 I’m also referring to JavaScript as well.
  4. 4. nt orta p ns im y rea so a re an es er form am att G eym ThNow I think it’s safe to say that games are pretty important, for many reasons.
  5. 5. sa l e r n iv ne u yo a re for ever es am e am e is a g G er ThOne of those reasons is that they are universal.There are games out there to suit all walks of life; whether that’s a board game, card game,or computer game. It’s all the same.Over the years, I’ve played all sorts of games that each meant something different to me atthat point in life.
  6. 6. It’s memories from games like Paperboy on the ZX Spectrum and its amazing noises and epicloading times.I sorely miss those days.
  7. 7. And Bomberman on the SNES, which really got me addicted to gaming.
  8. 8. And Lylat Wars on the Nintendo 64. Star Fox for the non-European folk.Do a barrel roll!
  9. 9. And the original Sim City.I don’t bare think about the hours I lost to that game, building a city on what I’ve only justnoticed was an incredibly muddy landscape.
  10. 10. And Red Alert, one of the first games I owned that let me play with others over the Internet. Itwas great fun!And probably one of my all-time favourites, along with the original Command and Conquer.Plus, it had an awesome soundtrack.
  11. 11. fu n n m them d a a re ple ha te es )peo am (sa ne G NoAnother reason is that they are incredibly fun to play.This is probably because they tap in to to our addictive, competitive personalities.I don’t know anyone who hates games.
  12. 12. However, I do know people who hate fruit. A lot.One of my favourite games at the moment is Fruit Ninja on the Kinect.It pretty much justifies the Kinect’s existence.I had a few friends over the other week and we all ended the weekend with Fruit Ninja-relatedinjuries.It was worth it though.
  13. 13. Trailer for Fruit Ninja -
  14. 14. ie s a r n d re o u wa h b rh ard u s , fa ste s p tter me er, be Ga BiggAside from being universal and fun, games are important because they push the boundariesof what’s possible with today’s technology.Games are one of the only things that deliberately use every ounce of your computer’scapabilities; from graphics, to processing power, to RAM, even to disk space.As computers constantly get better, games improve to use up the new improvements inspeed and power.And computer hardware is improved, in part, because of the desire to create faster and morerealistic games.
  15. 15. 2011 2002For example, this is Battlefield 3. It’s one of the most powerful and ‘realistic’ games out todate.It came out in 2011.Compare that to Battlefield 1942, which came out back in 2002.Notice the difference? There’s barely 9 years between them and yet it’s quite clear thatBattlefield 3 is far superior, at least visually.
  16. 16. Minimum specs 2400 2000 500 512 128 32 Processor (Mhz) Graphics (MB) RAM (MB) Battlefield 1942 (2002) Battlefield 3 (2011)Just take a look at the minimum hardware specs of Battlefield 1942 and Battlefield 3.In just 9 years we’ve pushed computers so far that the minimum requirement for a gametoday is way beyond what was even possible back in 2002.
  17. 17. Recommended specs 4000 2400 2400 2000 1024 500 512 32 128 Processor (Mhz) Graphics (MB) RAM (MB) Battlefield 1942 (2002) Battlefield 3 (2011) Battlefield 3 - Recommended (2011)And the minimum specs don’t even produce anything near the quality that you saw on theprevious slide.For that you need even more powerful hardware.These are the recommended specs for Battlefield 3. Aside from processor speed, they are atleast double everything else.We’re talking state of the art technology here, and even this still won’t run the game at its fullpotential.
  18. 18. e b r W ette mance a b erfor ean tte rp be s m sa nd e m w atu re Ga Ne feWe now have more and faster processors than ever before, we have insanely powerfulgraphics cards, and so much RAM we don’t know what to do with it.The improvements that games help bring about in computer hardware mean that we can nowdo some really cool stuff on the Web.Without games, there would be little need to continue pushing Web technologies; like fasterJavaScript, or hardware accelerated CSS and multimedia rendering.
  19. 19. e s ga m o re orw ard m ovef lay bm P the We lping he re ua YoSo in a rather long-winded way, my point here is that you need to play more games.You’re making the Web better and having fun at the same time. Win win!
  20. 20. es g a m ing ples ist exam Ex he be st ft eo SomThe number of HTML5 games out there is growing every day.I’d like to show you a selection of my favourites, just a tiny amount of what’s out there.
  21. 21. Quake IIFully-functional multiplayer Quake II port.
  22. 22. Cut The RopeCut The Rope, ported from iOS.
  23. 23. BejeweledBejeweled is a massively popular game on a whole variety of platforms.Popcap recently released a purely HTML5 version.
  24. 24. Command & ConquerCommand & Conquer: Tiberium Alliances is a HTML5 game from EA that is part real-timestrategy, part Farmville.
  25. 25. GT RacingGT Racing: Motor Academy is a 3D racing game by Gameloft and Mandreel.
  26. 26. BrowserQuestBrowserQuest is a massively-multiplayer RPG that Mozilla recently launched to the public.It works great on mobile and desktop devices but what’s even better is that, aside from beingan addictive game, the entire source code is on GitHub.http://browserquest.mozilla.org
  27. 27. g y o lo chn ick e st T 5g am e ML HT akes tm ftha stuf TheThere are key technologies that are involved in the development of HTML5 games like theones you just saw.I’m going highlight a few of my favourites.
  28. 28. vas an C tfo rm pla ics raph g 2DCanvas is a 2D bitmap graphics platform.It’s quite amazing what can be done with such simple drawing and image manipulation tools.In games this is used to do things like drawing sprites and performing image manipulationon the fly.
  29. 29. Silk is a stunning example of what can be achieved by combining the simple drawing toolsavailable in canvas.
  30. 30. Close Pixelate is a canvas app that lets you manipulate images on–the-fly to create apixelated effect.
  31. 31. You can even use canvas just for simple effects on a standard Web page.David Desandro uses canvas to draw curved lines on his portfolio that indicate areas of focus.Before canvas you’d have had to have used static images or complex techniques to achievethis.
  32. 32. Last year I helped HTML5 Doctor implement a canvas-based rollover effect on their elementindex.With canvas, we were able to create custom-shaped rollovers that were entirely dynamic.We also cached these canvas-generated images so they didn’t need to be created on everypage load.
  33. 33. Canvas <canvas id=myCanvasElement width=400 height=400></canvas>Using canvas is very straight forward.The first thing you need to do is add a canvas DOM element to your HTML page.
  34. 34. Canvas var canvas = document.getElementById(myCanvasElement);   var ctx = canvas.getContext(2d); ctx.fillStyle = "rgb(200,0,0)";   ctx.fillRect(10, 10, 55, 50);      ctx.fillStyle = "rgba(0, 0, 200, 0.5)";   ctx.fillRect(30, 30, 55, 50);From there you can then access the canvas through JavaScript to draw on it and do other coolstuff.This is small canvas demo that draws a solid red square underneath a blue one with halftransparency.‘myCanvasElement’ refers to a HTML <canvas> element that you’ll need to place in yourHTML file somewhere. In this example, I’m assuming that you’ve already done that.
  35. 35. GL eb W phics ra tedg ra ccele area ardw HWebGL brings the ability to provide hardware-accelerated graphics directly within thebrowser.Games use this to create immersive 3D worlds and models, or for faster 2D graphics.
  36. 36. HelloRacer is a little game that lets you drive a Formula One car around your browser. It’s abeautiful example of WebGL in action.
  37. 37. Rome is a music video created with WebGL. It’s an amazing example of what the technologycan achieve in a real-world situation given a large team.
  38. 38. Tinkercad is probably the best use of WebGL that I’ve seen in a production situation.It’s a Web app that allows you to create 3D objects in your browser using WebGL, then getthem printed and sent to your doorstep in just a few simple clicks. It’s seriously awesome.
  39. 39. Eve Online WebGL ship viewer.
  40. 40. Both Google Maps and Nokia have recently added support for WebGL. The Nokia version isparticularly impressive because they fully render and texture 3D shapes of buildings.
  41. 41. Undulating monkey by Paul Lewis.
  42. 42. I’m not going to lie, WebGL isn’t the easiest thing to learn. Then again, no raw 3D code isthat simple.Instead, I recommend checking out a library called three.js which abstracts WebGL and makesit much easier to implement.
  43. 43. m e Fra on ps ati ati on loo nim d anim estA timise qu Op rerequestAnimationFrame is the new, better way of managing animation in JavaScript.Instead of constantly running a setTimeout or setInterval function, which lack performanceand spike CPU usage, requestAnimationFrame puts the browser in control of things andkeeps things running smoothly.
  44. 44. requestAnimationFrame function update(timestamp) {   // DO SOMETHING   window.mozRequestAnimationFrame(update);   }   window.mozRequestAnimationFrame(update);In this example, I’m only using the Mozilla prefixed version of requestAnimationFrame. Inreality, there’s a really good shim by Paul Irish that handles cross-browserrequestAnimationFrame.
  45. 45. d io a u L5 usic TM nd m H grou ck ba nd ctsa effe nd SouHTML5 audio allows for plugin-less audio.For games, this would be used for sound effects and background music.Audio data APIs implemented by Mozilla and Google allow for manipulation of audio andmuch more fine-grained control.
  46. 46. This is something I made especially for the ASSEMBLY 2011 event in Finland.It’s an audio visualiser that uses WebGL and the HTML5 Audio Data API.
  47. 47. uses Soundcloud, the Audio Data API and canvas to render music as it plays.
  48. 48. Audio <audio id=myAudioElement controls>   <source src=audiofile.ogg type=audio/ogg> </audio>Like canvas, using audio is also straight forward.The first thing you need to do is add an audio DOM element to your HTML page.
  49. 49. Audio var audio = document.getElementById(myAudioElement);; audio.pause();From there you can then access the audio element through JavaScript to control it.
  50. 50. ge ra to kies cal s coo Lo than ore gm torin SMethods like the application cache, Local Storage, and IndexedDB are great for storingrelatively large quantities of data locally.This way you can cache data and allow the website to pick up where the user left off.
  51. 51. e ts ock bS ation e W omm un ic yerc ltipla MuWebSockets can be used for the real-time communication between a browser client andserver.For games, this would be used for fast-paced multiplayer functionality.
  52. 52. GoSquared use WebSockets for real-time website analytics.
  53. 53. WebSockets var ws = new WebSocket(; ws.send(This message is sent to the WebSocket server); ws.onmessage = function (event) {     console.log(;   }WebSockets are created entirely from JavaScript without the need to add elements to theHTML page.A new WebSocket connection can be opened by calling the ‘new WebSocket’ constructor andpassing it the URL to the WebSocket server.From there you can call the ‘send’ method to push data to the server.Or listen for the ‘onmessage’ event to handle data pushed to you from the server.
  54. 54. e rs ork b W aS cript e W eaded Jav i-thr MultWeb Workers allow you to run JavaScript in separate background threads.This allows you to offload computationally-heavy tasks with a single worker, or tackle largequantities of data in a fraction of the time by spreading tasks over multiple workers.Another benefit of doing this is that you don’t lock up the browser during heavy tasks,meaning a user can still interact with things and get stuff done.
  55. 55. Web Workers var worker = new Worker(my-worker.js); worker.onmessage = function(event) {    console.log(Worker message: +;   };Web Workers, like WebSockets, are created entirely through JavaScript.You create a new worker by calling the ‘new Worker’ constructor and passing it the path to aJavaScript file.You can then listen to the ‘onmessage’ event that will be fired every time the worker scriptsends data using a ‘postMessage’ method.
  56. 56. PI n A re e ul Sc we rf ull et po F im ple ,y SThe Full Screen API allows you to expand any HTML element to fill the users screen, even ifthe browser isn’t running full screen itself.For games, this is great because you can make the small canvas element fill the entire screen.Outside of games, this is useful for video elements and Web applications.
  57. 57. Full Screen API var canvas = document.getElementById(myCanvasElement); if (canvas.requestFullscreen) {     canvas.requestFullscreen(); } else if (canvas.mozRequestFullScreen) {     canvas.mozRequestFullScreen(); } else if (canvas.webkitRequestFullScreen) {     canvas.webkitRequestFullScreen(); }The Full Screen API can be requested from any DOM element.In this example you’re asking a canvas element to expand to fill the screen.One thing to note is that you can’t just make any element fill the screen whenever you want.Right now, the user has to click or press a key to initiate the Full Screen API.
  58. 58. P I A o ck ace r L pl te ne oin rso rino P cu he gt ockin LThe Pointer Lock API is an attempt at improving the mouse as an input device.It would be used in situations like games and 3D visualisations where the mouse positionrotates or moves you around a 3D space.As it stands there’d still be a cursor moving around the screen causing all sorts of troublewhen you want to click on something in your game.With the new API you can lock your mouse position and stop it from getting in the way andbeing a nuisance.This is available in both Firefox and Chrome.
  59. 59. P I d A p a eb me he W Ga et ot ol ns co he gt gin BrinThe Gamepad API is one of the major improvements to input that is coming.Both Mozilla and Google are working an an implementation of this and there is actually anexperimental build of Firefox available to the public that has it working. The API is also in thedev build of Chrome.What I find most interesting about the Gamepad API is that it might be just the thing we needto finally justify HTML5 gaming on a TV or console.Who wants to use a keyboard and mouse while sitting on the sofa?
  60. 60. This is a little demo that I put together to show off the Gamepad API implemented in mygame Rawkets.
  61. 61. P I n A a t io es n t de vic ri e ob ile n O on m ree ha ve Sc M ust-The Screen Orientation API allows you to do things like changing and locking, you guessed it,the orientation of the screen.Before now, it’s been incredibly difficult to lock orientation on a website or game usingnothing but JavaScript.
  62. 62. Screen Orientation API if (screen.mozLockOrientation) { screen.mozLockOrientation(landscape); }The Screen Orientation API is another relatively simple one.It just landed in Firefox Nightly on mobile.All you need to do is call the ‘lockOrientation’ method of the screen object and pass it aorientation string.It’s important to note that you also need to be using the Full Screen API for the orientationlock to work.
  63. 63. e.js od N cation uni m com rk etwo dn an gic ver lo SerNode is often used as a multiplayer game server, controlling the logic and handling theWebSockets connections to the players.It can be used for player authentication and the storage of data so gameplay can persist overmultiple game sessions.This is all made relatively easy with great third-party modules, like Socket.IO for WebSockets,and others that handle Redis and MongoDB for storage, for example.
  64. 64. n s tio plica bsite ap yw e eb ta fanc W ot jus NThe concept of Web apps is something that is gaining a lot of traction at the moment.It’s no doubt this this traction is as a result of the success of native applications and gameson the desktop and mobile, particularly with iOS and Android.
  65. 65. nce erie exp scre en like ho me p- op or Ap eskt thed from ch un LaSomething that needs to be tackled with Web apps is how to make them feel like realapplications rather than glorified websites.One way that is being considered is completely removing the browser chrome and runningthe application in it’s own window.This will effectively mean that you have full control of the app UI and it won’t look like it’sbeing run in a browser.
  66. 66. At Mozilla we call this WebRT, which stands for Web Run-Time.By using WebRT you can install a Web app directly into the OS just like you would a nativeapplication.The WebRT app will look and feel like a native application when launched but will actually berunning a browser rendering engine behind the scenes.This is an example of my game Rawkets running as a WebRT app with the Firefox renderingengine. Notice the lack of browser UI.
  67. 67. e s gin e n ay e m game st od Ga ML5 HT te CreaIf you haven’t already then I encourage you to give HTML5 game development a go.And you dont have to create an entire game infrastructure from scratch, you can use some ofthe existing engines that are proving popular.
  68. 68. Impact. A 2D game engine.I used this recently, and it’s really well made and has a good level editor and developmenttools.The documentation is great and the author is active and very helpful.
  69. 69. Crafty. Another 2D game engine.It’s a free engine and is doing much better than other free engines out there.
  70. 70. Isongenic Engine. A 2D to 2.5D game engine.Massively multiplayer networking built in, uses Node and MongoDB, and has canvas or DOM-based graphics.
  71. 71. ing ort e & p bas ion ec od e- vers a sin gl on ing C UsA lot of game developers want to target browsers but don’t want to rewrite their existinggames in JavaScript.To help this process, various methods of converting an existing code-base to JavaScript arestarting to appear.However, these methods also apply to non-games. Many people are now converting utilityscripts from native languages over to JavaScript. Things like SQLite, even Ruby!
  72. 72. Emscripten
  73. 73. PlayN and Google Web Toolkit
  74. 74. PhoneGap
  75. 75. u p g in zon eep ri K e ho th ff on tu uchs m SoI’ve really only touched the tip of the iceberg here.There is much more coming in the near future.Here are a few ways to keep up with things and get yourself prepared, particularly the thingshappening at Mozilla.
  76. 76. Are We Fun Yet?
  77. 77. Firefox Aurora“Get a first look at the latest developer tools, security features and innovative HTML5 andother Web technologies.”
  78. 78. Firefox NightlyBleeding edge functionality.Testing only.
  79. 79. Foundation HTML5 Canvas Out now Paperback and digital formats Become a canvas master Learn how to animate Make two cool space games RAWKES.COM/FOUNDATIONCANVASFoundation HTML5 Canvas is out now on Amazon and other reputable book stores.
  80. 80. HTML5 Games Most Wanted Out now Paperback and digital formats Learn from the best Various game-related tutorials Other tips and tricks APRESS.COM/9781430239789HTML5 Games Most Wanted is out now on Amazon and other reputable book stores.
  81. 81. O U Y s? K tion N ues A Q TH R b es wk es Ha wk ob ha ro @Thank you.If you have any questions feel free to grab me, or bug me on Twitter (@robhawkes).I’m a friendly chap and I’ll be happy to help.