Book Image

Canvas Cookbook

Book Image

Canvas Cookbook

Overview of this book

With the growing popularity of HTML5 Canvas, this book offers tailored recipes to help you develop portable applications, presentations, and games. The recipes are simple yet creative and build on each other. At every step, the book inspires the reader to develop his/her own recipe. From basic to advanced, every aspect of Canvas API has been covered to guide readers to develop their own application, presentation, or game.
Table of Contents (16 chapters)
Canvas Cookbook
About the Author
About the Reviewer


The world of gaming is very competitive, and day by day the technology is evolving and making things easier for users. HTML5 is a recent standard, which is flexible, interactive, and portable. It is supported by most browsers. This makes HTML5 a good language for developing applications with a wider reach.

The Canvas element in HTML5 is quite interesting as it allows programmers to render whatever they can imagine. Canvas allows users to draw 2D and 3D objects and render animation. HTML5 Canvas is therefore a suitable technology for developing applications and games for a variety of devices.

However, without a scripting language, HTML5 Canvas, is of limited use. A scripting language such as JavaScript is necessary to make use of HTML5 Canvas and is at the heart of any application or game.

Any application without style is an ordinary application that will not catch the eye of a user. Styling is important when it comes to developing applications commercially. It adds richness to the application. CSS helps developers do this.

This book is all about the usage of HTML5 Canvas, JavaScript, and CSS in the development of various recipes. The book starts with basic drawings on Canvas, graduates to animation and 3D rendering, and culminates with the development of games that can run on different devices. The recipes in each chapter are simple and crisp. The last few chapters exhibit the usage of third-party libraries such as Three.js and Phaser.js.

All recipes are supported with a precise explanation to inspire the reader to develop his or her own recipes.

What this book covers

Chapter 1, Paths and Text, is a simple chapter where you can view basic recipes to draw lines, arcs, curves, and text. It introduces the use of the Canvas API to render drawings.

Chapter 2, Shapes and Composites, introduces various shapes such as triangles, rectangles, circles, and ellipses. Coloring and styling is also demonstrated in a few recipes. You will find here exciting recipes rendering styled text and various types of composite.

Chapter 3, Animation, uses the drawings made in the previous chapter and adds some actions to them. It introduces a systematic approach toward animation. It covers basic movements such as linear motion, acceleration, oscillation, and its implementation through impressive recipes.

Chapter 4, Images and Videos, reveals the rendering of images and videos. The recipes show the clipping and cropping of images. Images on canvas are the basic foundation for any application or game.

Chapter 5, Interactivity through Events, introduces event handling. It encompasses events captured through input devices such as the mouse, keyboard, and touch. You will be able to create a simple game at the end of this chapter.

Chapter 6, Creating Graphs and Charts, displays different types of graph and chart. These are ideal for any data presentation. Here, I will show you to draw simple x and y axes and then plot different equations on them. You will learn to draw a bar chart and a pie chart.

Chapter 7, 3D Modeling, will show you the rendering of 3D objects. It will introduce you to an open source library named Three.js, used to draw various shapes such as cubes, spheres, cylinders, and toruses.

Chapter 8, Game Development, explains the complete procedure for developing a game. It is time to assemble all the nuts and bolts. I introduce here another open source library Phaser.js, which is one of the popular libraries for game development. You will learn various game stages, playing audio, creating and using sprites, and much more.

Chapter 9, Interoperability and Compatibility, is just an extension to the previous chapter, which highlights the deployment of the game on a mobile phone. You will encounter the use of CSS to enhance the look and feel of the game.

What you need for this book

The software required for trying out the recipes in this book are listed here:

  • Any browser that supports HTML5 Canvas and WebGL. I used Chrome Version 48.0.2564.116 m.

  • A web server to execute a few recipes that render images and video. I used IIS7.

  • Third-party libraries Three.js and Phaser.js.

  • You can create a repository on GitHub and register at to build your own applications for mobile phones.

All of these are easily available, and you can try the recipes on any platform. However, I tested the recipes on Windows 7 Professional.

Who this book is for

The book is intended for readers with a preliminary knowledge of JavaScript and CSS. Whether you're a beginner or expert in this technology, the book provides recipes to help you build your own application, presentation, or game.


In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section suggests the reader to make changes in the recipes and thereby develop his/her own recipes.


In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The on load property is responsible to invoke the init() function."

A block of code is set as follows:

  <title>Simple Lines</title>
    <script type="text/javascript">
      var can;
      var ctx;

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

function drawHorizontalLines()
        xs=10;  ys=10;xe=100; ye=10;
        c="teal"; w=2;  
        //draw 10 lines

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "If your browser doesn't support Canvas then it will display Your browser doesn't support Canvas as mentioned in the Canvas element of the HTML code."


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.


If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.