Book Image

HTML5 Canvas Cookbook

By : Eric Rowell
Book Image

HTML5 Canvas Cookbook

By: Eric Rowell

Overview of this book

The HTML5 canvas is revolutionizing graphics and visualizations on the Web. Powered by JavaScript, the HTML5 Canvas API enables web developers to create visualizations and animations right in the browser without Flash. Although the HTML5 Canvas is quickly becoming the standard for online graphics and interactivity, many developers fail to exercise all of the features that this powerful technology has to offer.The HTML5 Canvas Cookbook begins by covering the basics of the HTML5 Canvas API and then progresses by providing advanced techniques for handling features not directly supported by the API such as animation and canvas interactivity. It winds up by providing detailed templates for a few of the most common HTML5 canvas applications—data visualization, game development, and 3D modeling. It will acquaint you with interesting topics such as fractals, animation, physics, color models, and matrix mathematics. By the end of this book, you will have a solid understanding of the HTML5 Canvas API and a toolbox of techniques for creating any type of HTML5 Canvas application, limited only by the extent of your imagination.
Table of Contents (19 chapters)
HTML5 Canvas Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Canvas Security
Index

Preface

The HTML5 canvas is revolutionizing graphics and visualizations on the Web. Powered by JavaScript, the HTML5 Canvas API enables web developers to create visualizations and animations right in the browser without Flash. Although the HTML5 Canvas is quickly becoming the standard for online graphics and interactivity, many developers fail to exercise all of the features that this powerful technology has to offer.

The HTML5 Canvas Cookbook begins by covering the basics of the HTML5 Canvas API and then progresses by providing advanced techniques for handling features not directly supported by the API such as animation and canvas interactivity. It winds up by providing detailed templates for a few of the most common HTML5 canvas applications—data visualization, game development, and 3D modeling. It will acquaint you with interesting topics such as fractals, animation, physics, color models, and matrix mathematics.

By the end of this book, you will have a solid understanding of the HTML5 canvas API and a toolbox of techniques for creating any type of HTML5 canvas application, limited only by the extent of your imagination.

What this book covers

Chapter 1, Getting Started with Paths and Text, begins by covering the basics of sub-path drawing and then moves on to more advanced path drawing techniques by exploring algorithms to draw zigzags and spirals. Next, the chapter dives into text drawing and then completes with an exploration of fractals.

Chapter 2, Shape Drawing and Composites, begins by covering the basics of shape drawing and also shows you how to use color fills, gradient fills, and patterns. Next, the chapter takes an in-depth look at transparencies and composite operations, and then provides recipes for drawing more complex shapes such as clouds, gears, flowers, card suits, and even a full vector-style jet complete with layers and shading.

Chapter 3, Working with Images and Videos, covers the basics of image and video handling, shows you how to copy-and-paste sections of the canvas, and covers different types of pixel manipulation. The chapter also shows you how to convert images into data URLs, save a canvas drawing as an image, and load a canvas with a data URL. Finally, the chapter ends with a pixilated image focus algorithm that can be used to focus and blur images dynamically with pixel manipulation.

Chapter 4, Mastering Transformations, explores what’s possible with canvas transformations, including translations, scaling, rotations, mirror transforms, and free-form transformations. In addition, the chapter also explores the canvas state stack in detail.

Chapter 5, Bringing the Canvas to Life with Animation, begins by constructing an Animation class to handle an animation stage, and shows you how to create a linear motion, a quadratic motion, and an oscillating motion. Next, it covers some more complex animations such as the oscillation of a soap bubble, a swinging pendulum, and rotating mechanical gears. Finally, the chapter ends with a recipe for creating your own particle physics simulator, and also provides a recipe for creating hundreds of microscopic organisms inside the canvas to stress performance.

Chapter 6, Interacting with the Canvas: Attaching Event Listeners to Shapes and Regions, begins by constructing an Events class which extends the canvas API by providing a means for attaching event listeners to shapes and regions on the canvas. Next, the chapter covers techniques for getting the canvas mouse coordinates, detecting region events, detecting image events, detecting mobile touch events, and drag-and-drop. The chapter ends by providing a recipe for creating an image magnifier and another recipe for creating a drawing application.

Chapter 7, Creating Graphs and Charts, provides production-ready graph and chart classes, including a pie chart, a bar chart, an equation grapher, and a line chart.

Chapter 8, Saving the World with Game Development, gets you started with canvas game development by showing you how to create an entire side-scroller game called Canvas Hero. The chapter shows you how to create sprite sheets, create levels and boundary maps, create classes to handle the hero, the bad guys, the level, and the hero’s health, and also shows you how to structure the game engine using an MVC (model view controller) design pattern.

Chapter 9, Introducing WebGL, begins by constructing a WebGL wrapper class to simplify the WebGL API. The chapter introduces WebGL by showing you how to create a 3D plane and a rotating cube, and also shows you how to add textures and lighting to your models. The chapter ends by showing you how to create an entire 3D world that you can explore in first person.

Appendices A, B, and C discuss other special topics such as canvas support detection, security, canvas vs. CSS3 transitions and animations, and the performance of canvas applications on mobile devices.

What you need for this book

All you need to get started with HTML5 canvas is a modern browser such as Google Chrome, Firefox, Safari, Opera, or IE9, and a simple text editor such as notepad.

Who this book is for

This book is geared towards web developers who are familiar with HTML and JavaScript. It is written for both beginners and seasoned HTML5 developers with a good working knowledge of JavaScript.

What is HTML5 Canvas

Canvas was originally created by Apple in 2004 to implement Dashboard widgets and to power graphics in the Safari browser, and was later adopted by Firefox, Opera, and Google Chrome. Today, canvas is a part of the new HTML5 specification for next generation web technologies.

The HTML5 canvas is an HTML tag that you can embed inside an HTML document for the purpose of drawing graphics with JavaScript. Since the HTML5 canvas is a bitmap, every pixel drawn onto the canvas overrides pixels beneath it.

Here is the base template for all of the 2D HTML5 Canvas recipes for this book:

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
 
                // draw stuff here
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="578" height="200">
        </canvas>
    </body>
</html>

Notice that the canvas element is embedded inside the body of the HTML document, and is defined with an id, a width, and a height. JavaScript uses the id to reference the canvas tag, and the width and height are used to define the size of the drawing area. Once the canvas tag has been accessed with document.getElementById(), we can then define a 2D context with:

var context = canvas.getContext("2d");

Although most of this book covers the 2D context, the final chapter, Chapter 9, uses a 3D context to render 3D graphics with WebGL.

Conventions

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

Code words in text are shown as follows: "Define the Events constructor."

A block of code is set as follows:

var Events = function(canvasId){
    this.canvas = document.getElementById(canvasId);
    this.context = this.canvas.getContext("2d");
    this.stage = undefined;
    this.listening = false;
};

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

var Events = function(canvasId){
    this.canvas = document.getElementById(canvasId);
    this.context = this.canvas.getContext("2d");
    this.stage = undefined;
    this.listening = false;
};

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "It writes out the text Hello Logo! at the origin."

Note

Warnings or important notes appear in a box like this.

Tip

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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail .

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 on www.packtpub.com/authors.

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 for this book

You can run the demos and download the resources for this book from www.html5canvastutorials.com/cookbook, or you can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Errata

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 would 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 http://www.packtpub.com/support, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.