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

Drawing an ellipse


Drawing an ellipse is just an implementation of translation and scaling. The output is quite simple:

How to do it…

The recipe goes like this.

The HTML code:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body onload="init()">
<canvas id="myCanvas" width="578" height="200" style="border:3px solid blue"></canvas>
<script src="ellipse.js">
</script>
</body>
</html>

The JavaScript code:

function init()
{
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var centerX = 0;
      var centerY = 0;
      var radius = 50;
      // translate context
      context.translate(canvas.width / 2, canvas.height / 2);
      // scale context horizontally
      context.scale(2, 1);
      // draw circle which will be stretched into an ellipse
      context.beginPath();
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

      context.lineWidth = 5;
      context.strokeStyle...