Chapter 10. Taking Things Further and the Future of Canvas

In this last chapter, I'll walk you through some of the ways to take things further with animation and game development. I'll also highlight some of the issues surrounding canvas and it's future, like the comparison with Flash and other technologies.

Canvas and SVG

Back in Chapter 1, I mentioned that SVG is often considered part of HTML5, when in reality it's actually a completely different technology. It's massively important to be aware of SVG, as it provides functionality that is very similar to that of canvas. It's also important to know the difference between SVG and canvas, as these differences will decide which of the two technologies you should be using.

SVG is another 2d drawing platform that is available within the browser, and that doesn't require plug-ins like Adobe Flash. As I mentioned in Chapter 1, SVG stands for Scalable Vector Graphics, which sort of gives away its major feature — vector graphics. In comparison, canvas uses bitmap graphics, but I'll explain the difference in more detail shortly.

Graphics are created in SVG by utilising the DOM, and everything that is drawn is created within a separate DOM element. For example, the following is the definition of a rectangle in SVG:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="200">
        <rect x="50" y="50" width="200" height="100" fill="#000000"/>
</svg>

Notice how all the attributes of the shapes are defined within the DOM element? This is a massive difference to canvas, in which everything is drawn within a single element, using JavaScript instead of the DOM.

There are many benefits to drawing shapes in the DOM like this, but one of the most valuable is that it allows you to access and edit a shape after you've drawn it. This is something that you can't do in canvas, as you'd need to wipe the canvas clean and redraw the shape again. In SVG there is nothing to wipe clean; you just edit the properties of each shape in the DOM, and it will update automatically.

A good way to compare to two technologies is by thinking of canvas as Microsoft Paint back in the day, where the only way that you can edit or change anything is by erasing it all and starting again. In comparison, SVG is more like Adobe Illustrator, where shapes are selectable and editable, and infinitely resizable.

Note

It's worth mentioning that inline SVG support is pretty lacking in browsers at the moment. Fortunately all the major manufacturers seem to be working on supporting it, so watch this space. I'd certainly keep an eye on the "When can I use" web site for more up to date information http://caniuse.com/#feat=svg-html5.

Accessibility

Another huge benefit to SVG is that it's accessible. In canvas, everything that you draw is created using pixels, so the canvas is completely unaware of what's actually on it. For example, you might draw a circle using the arc method, but as far as the canvas is aware you've just changed the color of a specific area of pixels, even though they happen to look like a circle to the human eye. With SVG, you can access every shape and its data by traversing through the DOM. This allows you to pull data back out of SVG, and to also be aware of the kind of shapes that have been drawn and their properties (like size, position, and so on).

Bitmap vs. vector

As I mentioned previously, SVG is vector graphics, and canvas is bitmap graphics. What does this actually mean? In short, a lot!

Bitmap graphics (a.k.a. raster graphics) are stored as pixels in a 1-to-1 format (see Figure 10-1). What this means is that if you draw a one pixel square in bitmap, it will only ever exist as one pixel. If you tried to change that pixel, like resizing it, the single pixel would become pixellated and distorted. This is because the bitmap graphic has absolutely no idea about the type of shape that it represents. If you enlarged the one pixel square to say five pixels square, that single pixel would be stretched to five times the size, causing the new five pixel square to look fuzzy. I';m sure that you've noticed this effect before, perhaps when resizing a JPEG image.

Bitmap vs. vector

Figure 10.1. Bitmap vs. vector

On the other hand, vector graphics are stored as coordinates that describe the shape that you want to draw (again, see Figure 10-1). The benefit to this method is that pixels don't get involved until you actually want to visualize the vector graphic on a screen. This means that you can resize a vector graphic as much as you want and the resulting output in pixels will stay crisp and clean. The process going on here is simple; the coordinates of the shape are resized, but keep the same relationship between each other, then the new coordinates are converted into pixels to be displayed.

There are both massive pros and cons to canvas and SVG. For example, SVG is great for accessibility and for visualizing data that you want to be able to insert and pull out of the drawing at a later date (because it uses the DOM). Canvas, on the other hand, is fast and perfect for detailed pixel-level drawing, like manipulating images and video. It's worth weighing up the options before deciding which technology that you want to use. I wouldn't worry too much about it though; it's not a life-or-death decision.

Note

If you want to start playing with SVG then I'd highly recommend trying out the Raphaël JavaScript library at http://raphaeljs.com. It's a painless way to experiment with SVG without getting too caught up in setting everything up and creating all the individual DOM elements.

Canvas and Flash

It seems that you can't go anywhere these days without someone claiming that canvas is a Flash killer, or that Flash is better than canvas. It's actually quite annoying, because there really isn't a battle between the two technologies; they serve completely different purposes!

Flash was created many years ago, and has evolved to solve some of the issues surrounding animation and multimedia on the Web. At the time, there were no native methods of drawing 2d graphics within the browser, or embedding video and audio. Flash solved these problems by providing a plugin that worked consistently across most, if not all browsers and platforms. It was a lifesaver!

Since then, Flash has evolved into something much bigger. In fact, Flash has matured into a solid platform that lets you produce fast animated graphics, encode video, and create complicated games. It also does a lot more, including network communications and integration with peripheral devices. Obviously I';m leaving out many of its features, but you get the gist.

Canvas was created to solve the problem of requiring a native method of drawing 2d graphics within the browser, without depending on a plugin being installed. It was created to utilise existing technologies like HTML and JavaScript. In short, canvas was created to provide an alternative solution for drawing and animating graphics within a browser. Simple!

I suppose what I';m getting at here is that canvas and Flash were created for different purposes. They solve different problems, and there is no need for there to be conflict between them. In my opinion, they shouldn't be compared, and it should be a case of using the right tool for the job.

JavaScript developers can learn from Flash

My friend, Seb Lee-Delisle, helped me put Flash and canvas into perspective. He said that canvas is at a stage of development that Flash was at many years ago (which is true), and that JavaScript developers can learn from the Flash developers that have gone through all this before.

He's absolutely right. Canvas is still not mainstream, and therefore not many people develop with it. The state of canvas means that JavaScript developers are still experimenting with it, trying to push it as far as possible to learn what can actually be done with it. The truth is that these experiments and the resulting lessons learned are very similar to the ones learned by the developers who pushed Flash to its limits all those years ago.

Seb's message is simple: stop trying to differentiate yourselves from each other, have a hug, and share your knowledge. If you can do that, then I can guarantee you that canvas will have a much brighter future.

Canvas doesn't have a user-friendly editor like Flash

One argument on the side of Flash is that it's difficult to use canvas because it doesn't have an application that makes it easy to work with, like the Flash IDE. Fortunately, this is no longer true.

There is a whole host of options available to canvas developers that help make the process of producing animations and games much easier. Some of these options are Radi (http://radiapp.com), which is a dedicated application to create HTML5 animation (see Figure 10-2), and ai2canvas, an Adobe Illustrator plug-in.

In all honestly, I wouldn't be surprised if Flash itself offers an option to export directly to canvas; I know Adobe are definitely toying with the concept.

The Radi HTML5 animation application

Figure 10.2. The Radi HTML5 animation application

In general, there is rarely an argument raised about Flash and canvas that can't be brushed aside with a little bit of sensible thinking. So next time someone asks you why they should use canvas instead of Flash, consider telling them that they shouldn't. That'll surprise them!

Canvas and performance

One of the most obvious limitations of canvas at the moment is that of performance. I';m not going to lie to you, it's pretty shocking at the moment. The reason for this is because most browsers use the CPU to render the canvas, which means that the processor quickly gets overwhelmed and the canvas grinds to a halt. Admittedly, this only happens when you're trying to create a complicated animation, or draw lots and lots of objects, but it's still a problem.

The good news is that there is a solution, and it's called hardware acceleration. The even better news is that the solution is available for you to experiment with today. What's surprising is that IE9 is one of the forerunners in canvas hardware acceleration, with a few other browsers in Windows following suit. Unfortunately, no browser on the Mac supports proper hardware acceleration just yet, but I';m sure that this will change soon.

Note

Interestingly, although IE9 is a major improvement to the Microsoft range of browsers, it won't be available on Windows XP. This means that users of those older versions of Windows will be without the amazing new Web technologies that are on the horizon. However, it's arguable that they should really be thinking about upgrading from XP by now.

Hardware acceleration is the delegation of the drawing processes of canvas to the GPU on the graphics card. This frees up the CPU and allows the GPU to do what it does best: crunching through hardcore graphics-related tasks. The difference that hardware acceleration brings about is immense, and it's immediately obvious. I'd encourage you to play a canvas animation through on a browser that isn't hardware accelerated, and then again on a browser that is. If anything, the accelerated browser will probably feel a lot smoother.

Testing for performance

Hardware acceleration is definitely not a magic bullet; it can't solve all performance related problems. Some of the most common issues with performance can be solved quite simply. For example, too many loops in collision detection routines can cause all sorts of headaches. Another example would be using overly complicated mathematical calculations when you could achieve the same effect with an arbitrary number (like how you achieved friction in Chapter 7).

This is where the lessons from experienced Flash developers come into play. These are the guys that have gone through the hardships involved with squeezing every ounce of performance out of an animation loop. These are the guys that can teach you the tricks of the trade, like the little performance tips that add up to create some pretty noticeable gains.

If you want to do your own testing with performance, then I'd definitely check out jsPerf (http://jsperf.com). This benchmarking tool allows you to test various methods that achieve the same end goal; ultimately letting you work out if one is faster than the other. It's not foolproof, but it's certainly a great way of quickly finding out whether you can squeeze a bit more out of your code.

Canvas gaming and animation libraries

As far as what you've learned in this book, you should now have all the basic knowledge to go out and start creating your own games and animations from scratch. But what if you don't want to create them from scratch all the time? What if you want the everyday tasks like animation loops taken care of for you? This is where the influx of new animation and gaming libraries for HTML5 come in.

These libraries, like Impact (http://impactjs.com, shown in Figure 10-3), allow you to put together games and animations without having to worry about the nitty gritty. In essence, these libraries work in exactly the same way as jQuery; they abstract away the complexities, which allow you to worry about what you're making, instead of how you're making it.

The Impact game library

Figure 10.3. The Impact game library

At the time of writing, there are numerous libraries to choose from (https://github.com/bebraw/jswiki/wiki/Game-Engines). Aside from Impact, another of the most prominent libraries is Easel (http://easeljs.com, shown in Figure 10-4). This is less of a dedicated gaming library, and more of a general helper library for animating with the canvas element.

If you're a Flash developer, then you'll notice straight away that Easel uses a lot of concepts from ActionScript; like display objects, and a stage. This isn't by accident. The developer, Grant Skinner, is well known for his Flash skills and says himself that Easel is "loosely based on Flash's display list, and should be easy to pick up for both JS and AS3 developers."

The Easel animation library

Figure 10.4. The Easel animation library

These libraries are good, but it's impossible for them to provide absolutely everything that you'll need. I'd recommend not jumping in and relying on them to do all the work for you. If you first learn the core concepts of animation and game development, then you'll have a solid standing for tackling issues, and attempting unique tasks that the libraries might not support.

Going into the third dimension

So far everything that you've created within the canvas has been two-dimensional. If this bores you, then you'll be mighty excited to know that three-dimensional graphics are coming to canvas under the guise of a technology called WebGL. It's not supported in all browsers (only Chrome and development versions of Webkit and Firefox at the time of writing), but it's still pretty cool.

If you'd like to try it today then I'd highly recommend giving the three.js library by Mr.doob a go (https://github.com/mrdoob/three.js). This library tries to lower the barrier for entry to WebGL (which is admittedly quite high) by making it as easy as possible to create awesome 3d graphics with as little code as possible (see Figure 10-5).

Mr.doob's 3d globe created using three.js

Figure 10.5. Mr.doob's 3d globe created using three.js

I'd be lying if I said 3d graphics in canvas wasn't complicated, but it doesn't make it any less fun. I'd certainly take a look at it, even if you don't plan to use it.

Integration with peripheral devices

A major area that browsers haven't cracked yet is that of interfacing with connected peripheral devices, like webcams and microphones. This is an area that Flash is particularly experienced in, and is one that is only just starting to see the light of day in a format that uses no plug-ins.

There's actually a group of people whose sole job is to come up with the specification for this communication between a browser and connected devices. The group is called the Device and APIs Policy Working Group, or DAP for short, and their work on the Media Capture API is what's most interesting, in my opinion.

It would be the Media Capture API that allows JavaScript developers to access images from a webcam and to then manipulate them or use them in some way. For example, you could build in face detection, a simple set of filters (like Photo Booth on the Mac), or perhaps even video streaming through something like WebSockets? Who knows. The possibilities are endless.

You should definitely check out the official website for the DAP group; it's very interesting to see the kind of stuff that's being worked on (www.w3.org/2009/dap/).

Project Rainbow

So far, there isn't much to show from the DAP, but at the time of writing Mozilla have already started experimenting with accessing the webcam and microphone through JavaScript. This experiment is called Rainbow (https://mozillalabs.com/rainbow/), and it's beginning to look really promising. As it stands, you can access a webcam and microphone, and then record them to an open format video file. The resulting file can then be accessed through JavaScript so you can manipulate it, or even upload it to a server. It's really cool!

The project Rainbow web site

Figure 10.6. The project Rainbow web site

One of the coolest, most interesting features of Rainbow is its ability to record the contents of the canvas. What this allows you to do is record an animation, or perhaps a gaming session, and save it as a video file. It basically removes the need to use applications that record your entire desktop.

Multiplayer with WebSockets

Both of the games that you've created in this book are single player. Although, they could quite easily be made multiplayer by adding some simple logic for more than one player, like using a different set of keys for player two to move another rocket in the last game. However, this would still require both players to be playing on the same computer, and both using the same keyboard. WebSockets would allow you to make your game truly multiplayer over a network, like the Internet.

WebSockets aren't actually anything to do with games; they're a method of communicating data back and forth in realtime, as described at the end of Chapter 1. On their own, WebSockets aren't that exciting, but that excitement grows infinitely when you start to combine WebSockets with other technologies, like canvas.

Being able to tie the data being sent back and forth via WebSockets to a visual display (the canvas) unlocks a whole host of possibilities. For example, you could send the (x, y) coordinate position of a player to a server, using WebSockets, and then have that position sent by the server to every other player connected to the game, using WebSockets. That (x, y) position could then be used to display all the other players in the game. This is a really basic example of multiplayer, but it's exactly how I started with Rawkets (http://rawkets.com), my own multiplayer game that uses canvas and WebSockets (see Figure 10-7).

My multiplayer canvas and WebSockets game, Rawkets

Figure 10.7. My multiplayer canvas and WebSockets game, Rawkets

As with everything else in this section, WebSockets aren't super easy, but that doesn't meant that you shouldn't go off and learn about them. I encourage you to explore what WebSockets can do for you, and to experiment with creating your own multiplayer game. This is another section that I could write an entire book about, but I hope that I've given you enough to get excited about WebSockets enough to consider them in the future.

Inspiration

Before I leave you, I thought it would be a good idea to give you some inspiration in the form of great HTML5 games that have been created during the writing of this book. Enjoy!

Sketch Out

This is a fantastically immersive space-based game that throws you feet first into an epic battle with another planet-type entity. Your job is to draw defenses around your planet and protect it from being hit. The music is great as well; so atmospheric. Check it out at http://sketch-out.appspot.com/.

Sketch Out by Fi

Figure 10.8. Sketch Out by Fi

Z-Type

This is a weirdly addictive game, based on words. That's right, the entire game is based around typing in the words that appear on the screen, with each correct letter landing a direct shot on your opponent. Cool! Check it out at www.phoboslab.org/ztype/.

Z-Type by Dominic Szablewski (image from Mozilla Labs)

Figure 10.9. Z-Type by Dominic Szablewski (image from Mozilla Labs)

Sinuous

This is a pretty cool game, and it's very similar in functionality to the asteroid avoidance game that you made in the previous chapter. In fact, Sinuous is much more advanced and it a great example of exactly what can be achieved when you use the techniques from this game alongside some time and effort. Check it out at http://sinuousgame.com/.

Sinuous by Hakim El Hattab

Figure 10.10. Sinuous by Hakim El Hattab

Summary, and farewell

In this chapter I've explored some of the areas relating to canvas and it's future for animation and gaming. I've also highlighted some of the technologies that canvas is often compared to, hopefully allowing you to make an educated decision about which one to use for your projects.

Some of these topics could perhaps have come earlier in the book, but I felt that together they combined to shed some light on the future of canvas. Overall, canvas has a massively bright future, and you should be excited to be around during its development. Learn how to use canvas today, and who knows what kind of cool stuff you'll be able to create in the near future!

But really, we're only at the beginning of canvas' journey. Technologies like hardware acceleration and WebGL are still yet to be supported cross-platform. It's these technologies that are really going to shape how canvas is used in the future; they're going to help define its purpose.

All in all, canvas is a massively awesome addition to your toolkit, especially when combined with WebSockets, and other HTML5 technologies, like video and audio. I hope that this book has inspired you to experiment with it, even if it's just to see what can actually be achieved.

I'd love to hear about the kind of stuff that you get up to. So what are you waiting for? Go forth and be amazing!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.72.74