Creating a simple bar chart
Now that you have a working environment set up, let's get started and create a simple bar chart. You can type in the code as we go along, but you can also download the full working examples from the GitHub repository for this chapter. Each screenshot and code listing in this book contains a reference to the file used to produce it.
Setting up the graphics context
Charts are displayed inside the graphics context provided by an HTML Canvas object. There are many ways to create one; the simplest way is to use plain HTML. Place a <canvas>
element somewhere inside <body>
. It should have an ID
attribute, as follows:
<canvas id="my-bar-chart" width="200" height="200"></canvas>
Chart.js graphics are responsive by default. The chart will fit in the available space: the height
and width
attributes won't affect the actual size of the chart (unless you change the defaults).
You can obtain a JavaScript handle to the canvas
object using DOM (or JQuery) in...