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
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Animating a line


This animated line recipe shows a very basic animation, in which the line moves to and fro. The output of the recipe is shown here:

How to do it…

The actual output is a single canvas with the animated line. The previous image tries to help you visualize the frames in different stages of the animation. You need to try this example to get a feel. The code is given as follows:

The HTML code:

<html>
<head>
<title>A simple line animation</title>
<script src="LineAnimation.js"></script>
</head>
<body onload="init();">
<canvas id="MyCanvasArea" width="300" height="200" style="border:2px solid blue;" >
   your browser does not support canvas
</canvas>
<h1>An animated line</h1>
</body>
</html>

The JavaScript file, as mentioned in the <script> tag in the previous code:

var x =  0;
var y = 80;
var xEnd=200;
var goRight=true;
var canvas;
var context;
function animate() {   
reqAnimFrame = window.mozRequestAnimationFrame...