Using Chart.js to make and work with canvas charts with javaScript

These days I am working out some projects that have to do with analyzing text, and it would be nice to find a way to visualize that data with canvas elements. I was thinking of making my own solution, but I am glad that I have found charts.js as it is pretty much just what I had in mind, and seems to work great!

Basic example of charts.js use

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<div style="width:320px;">
<canvas id="chart-demo-1"></canvas>
</div>
<script>
var ctx = document.getElementById('chart-demo-1').getContext('2d'),
// chart
chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['week1', 'week2', 'week3'],
datasets: [{
label: 'impressions',
borderColor: '#ff0000',
data: [450, 375, 680]
},{
label: 'clicks',
borderColor: '#0000ff',
data: [70, 20, 120]
}]
}
});
</script>

updating a chart

Updating a chart is as simple as just changing the dataset values and calling the chart.update method in the instance of Chart that is returned when calling the constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
setInterval(function(){
chart.data.datasets.forEach(function(ds){
ds.data = ds.data.map(function(){
return Math.floor(Math.random() * 50);
});
});
chart.update();
},1000);



Conclusion

Chart.js is pretty cool for doing anything with charts. I just wanted to put together a quick post on this one, I will likely write more about it in the future.