Visualising data in javascript can be done in a lot of different ways. You can do it just using html, you can use one out of a lot of library, you can draw on a canvas like we did with p5. In some ways data does not need to be visualised, what if some data was connected to sound fx.
In these lectures we will focus mainly on creating graphs using chart.js. Chart.js is a javascript library for creating graphs and it has been selected for these reasons
It sits in the sweetspot between looking pretty and not being to complicated
It is used and recommended by a lot of developers
It covers most basic graph usecases
Another really big and popular datavis library is D3. It is not covered in these lectures, but feel free to try it out!
Learning objectives
Visualising using Chart.js
Get json data into javascript
Teacher instruction
Work in pairs first 20 minutes. Afterwards you decide yourself
Today will be a lot of you exploring the chart.js api and documentation
Let's first setup the html so we are ready to use chart.js
There are two important things we need to do:
Import the chart.js library. That is done here <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"> It works exactly like when we import our main.js file, the only difference is that the directory of the file is in the cloud. If you want to see the code you can go to https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js. The code is minified which means it has been changed so the file takes up less space. But the javascript enables us to create the graphs
Create a canvas html tag for the graphs to go into. Chart.js uses canvas to draw the graphs. The canvas html object we have worked with when using P5. It is used to draw shapes onto. Wrap the canvas in div tags to make it responsive <canvas id="chart"></canvas>
Setup the javascript
On the first line we select the canvas using document.querySelector and get the context for the canvas so we can draw on it.
Now we create a new instance of a class called Chart (this is a class we get from importing the chart.min.jsin the head). You dont need to understand classes and instances but if you are interested watch this video. When creating a new Chart, we need to give it two arguments:
The context from the canvas so we can draw on the canvas
An object that will decide everything about how the graph will be shown
The object has 4 top level keys
type: Decides the type of the graph
data: Decides the data to use
options: Used for things like interaction, legends and a lot more
plugins: Can contain plugins
CleanShot 2022-09-07 at 10.57.16
Events
To trigger an event when a click occurs use the following code
More things
In the documentation it is documented how to do lots of things in chart.js. These are things like
Labels
Legends
Scales
Color
Background
It does not make sense for me to document everything here since the documentation is pretty good.