Chart.js

Canvas:

To draw a line chart we need to create a canvas element in our HTML in which Chart.js can draw our chart.

<canvas id="buyers" width="600" height="400"></canvas>

Next, we need to write a script that will retrieve the context of the canvas inside a <script> tag.

var buyers = document.getElementById('buyers').getContext('2d'); new Chart(buyers).Line(buyerData);

Inside the same script tags we need to create our data, in this instance it’s an object that contains labels for the base of our chart and datasets to describe the values on the chart.

var buyerData = { ` labels : [“January”,”February”,”March”,”April”,”May”,”June”], datasets : [ { fillColor : “rgba(172,194,132,0.4)”, strokeColor : “#ACC26D”, pointColor : “#fff”, pointStrokeColor : “#9DB86D”, data : [203,156,99,251,305,247] } ] }`

First, we need the <canvas> element.

Next, we need to get the context and to instantiate the chart inside a container.

new Chart(countries).Pie(pieData, pieOptions);

Next we need to create the data. This data is a little different to the line chart we just need to supply a value and a color for each section:

Example:

var pieData = [ ` { value: 20, color:”#878BB6” }, { value : 40, color : “#4ACAB4” }, { value : 10, color : “#FF8153” }, ];`

Now, immediately after the pieData we’ll add our options:

var pieOptions = { ` segmentShowStroke : false, animateScale : true }`

The syntax for the bar chart is very similar to the line chart.

new Chart(income).Bar(barData);

Example:

var barData = { ` labels : [“January”,”February”,”March”,”April”,”May”,”June”], datasets : [ { fillColor : “#48A497”, strokeColor : “#48A4D1”, data : [456,479,324,569,702,600] }, { fillColor : “rgba(73,188,170,0.4)”, strokeColor : “rgba(72,174,209,0.4)”, data : [364,504,605,400,345,320] } ] }`

Drawing rectangles:

There are three functions that draw rectangles on the canvas:

  1. fillRect(x, y, width, height): Draws a filled rectangle.
  2. strokeRect(x, y, width, height): Draws a rectangular outline.
  3. clearRect(x, y, width, height): Clears the specified rectangular area, making it fully transparent.

Each of these three functions takes the same parameters. x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle’s size.

Drawing paths:

A path is a list of points, connected by segments of lines that can be of different shapes, curved or not, of different width and of different color.

Drawing text:

The canvas rendering context provides two methods to render text:

  1. fillText(text, x, y [, maxWidth]) : Fills a given text at the given (x,y) position. Optionally with a maximum width to draw.

  2. strokeText(text, x, y [, maxWidth]) : Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw.