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

Drawing rectangles

There are three different functions in the canvas API to draw rectangles. They are:

  • rect(xPos,yPos,width,height)

  • fillRect(xPos,yPos,width,height)

  • strokeRect(xPos,yPos,width,height)

Let's see these all together in a single recipe. So here is the output of our first recipe:

How to do it…

The output that shows three different rectangles, uses a call to three different functions, which are explained further. The recipe is as follows.

An HTML file that includes the canvas element:

<script src="Rectangles.js"></script>
<body onload="init()" bgcolor="#FFFFCC">
<canvas id="canvas" width="250" height="200" style="border:2px solid blue;" >
  your browser does not support canvas

The JavaScript file as mentioned in the <script> tag in the previously given code:

function init()
  var canvas = document.getElementById...