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 a bar graph


Another typical representation, which is widely used, is the bar graph. Here is an output of this recipe:

How to do it…

The HTML code is as follows:

<html>
<head>
  <title>A simple Bar chart</title>
  <script src="bargraph.js"></script>
</head>
<body onload=init()>
  <h1>Your WhatsApp Usage</h1>
  <canvas width="600" height="500" id="MyCanvasArea" style="border:2px solid blue;" tabindex="0">
    Canvas tag is not supported by your browser
  </canvas>
</body>
</html>

The JavaScript code is as follows:

function init(){
  var gCanvas = document.getElementById('MyCanvasArea');
  // Ensure that the element is available within the DOM
  var ctx = gCanvas.getContext('2d');
  // Bar chart data
  var data = new Array(7);
  data[0] = "MON,130";    data[1] = "TUE,140";    data[2] = "WED,150";
  data[3] = "THU,140";    data[4] = "FRI,170";  data[5] = "SAT,250";
  data[6] = "SUN,340";

  // Draw the bar...