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 any script block or file loaded by your HTML file, as shown in the following code snippet (the script block will be ignored in most JavaScript listings in this book):

<script>
const canvas = document.getElementById("my-bar-chart");
</script>

You can also dynamically create a <canvas> object using Document Object Model (DOM), or JQuery. In this case, an ID attribute is not strictly necessary, since the variable itself can be used as a handle, but it's good practice to define one, as follows:

canvas canvas = document.createElement("canvas");
canvas.setAttribute("id","my-bar-chart");
document.body.appendChild(canvas);

A chart is created using the Chart() constructor. It receives two arguments: the graphics context of the canvas where the chart will be displayed, and an object containing the chart data, as demonstrated in the following code:

const chartObj = {…}; // the chart data is here
const context = canvas.getContext("2d");
new Chart(context, chartObj); // this will display the chart in the canvas

If your canvas object has declared an ID attribute, you don't need a context object. You can simply use the ID attribute as the first argument, as follows:

new Chart("my-bar-chart", chartObj);

The object that contains the chart data requires at least two properties: type, which selects one of the eight different kinds of Chart.js charts; and data, which references an object containing the datasets and properties of the data to be displayed, as follows:

const chartObj = {type: "bar", data: dataObj};

Normally, the chart object is configured inside the constructor, as follows:

new Chart("my-bar-chart", {type: "bar", data: dataObj});

This is the basic setup for any chart created with Chart.js. It won't show any chart yet, because we didn't provide any data, but if your library loaded correctly, you should see an empty axis. The code is in the Templates/BasicTemplate.html file.

If nothing shows up in your screen, there may be a syntax error in your code. Check your browser's JavaScript console. It's always a good idea to keep it open when you are working with JavaScript, so that errors can be detected and fixed quickly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset