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 line graph


Graphs are always informative. The basic graphical representation can be a line graph, which is demonstrated here:

How to do it…

The HTML code is as follows:

<html>
<head>
  <title>A simple Line chart</title>
  <script src="linechart.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] = "1,130";    data[1] = "2,140";    data[2] = "3,150";    data[3] = "4,140";
  data[4] = "5,180";  data[5] = "6,240";  data[6] = "7,340";
  // Draw the bar chart...