Three things you can learn in chart.js from mimicking Nyan cat

ChartJS is a great javascript framework to customise your own charts. It is so flexible and powerful, that in this blog you will mimic the viral Nyan cat to learn to:

  1. Update data sets in a graph with .update()
  2. Replace a data point with an image using new Image() (this is where the Nyan cat will be placed)
  3. Create a filled line chart with multiple gradient colours

You can find the live demo in codepen or in jsfiddle .

Let’s start with the basics

Installing Chart.js

Install chart.js by adding its CDN link to the <head> of your code.

https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js">

Creating the container for your graph in the HTML

Chart.js uses canvases to add the graphs. Start by including a <canvas> tag in your .html with an id attribute. In this example, we’ll set the height to 300px, but feel free to set it to any other value that suits you.

<canvas id="nyancat" height="300px"></canvas>

Selecting the data points

To give the impression that the waves are moving, we’ll need to alternate between two data sets. The x-axis position of the data points in both datasets are identical. We will only change the y-axis position, so that certain data points go up and down.

For this example, we’ll use these two data sets in the .js file:

var dataSet1 = [{
'position': 'x1',
'height': 150
},
..., {
'position': 'x8',
'height': 400
}]
var dataSet2 = [{
'position': 'x1',
'height': 150
},
..., {
'position': 'x8',
'height': 300
}]

Creating the colourful gradient of the chart

In my previous blog, we created a gradient chart that changed in colour from from left to right. In this new chart, we’ll create a gradient that changes colour from top to bottom.

We first need a variable to store our gradient, so let’s add the following:

var ctx = document.getElementById("nyancat").getContext("2d");

getContext("2d") will return an object that provides methods and properties for drawing on our canvas with the id nyancat.

We will now add the colours for the stroke and the fill:

//creating the gradient of the line in the chart
var gradientStroke = ctx.createLinearGradient(0, 0, 0, 300);
gradientStroke.addColorStop(0.25, "rgba(244, 67, 54, 1)");
gradientStroke.addColorStop(0.35, "rgba(255, 152, 0, 1)");
gradientStroke.addColorStop(0.5, "rgba(255, 235, 59, 1)");
gradientStroke.addColorStop(0.6, "rgba(76, 175, 80, 1)");
gradientStroke.addColorStop(0.8, "rgba(33, 150, 243, 1)");
gradientStroke.addColorStop(1, "rgba(103, 58, 183, 1)");
//creating the gradient of the fill in the chart
var gradientFill = ctx.createLinearGradient(0, 0, 0, 300);
gradientFill.addColorStop(0.25, "rgba(244, 67, 54, 1)");
gradientFill.addColorStop(0.35, "rgba(255, 152, 0, 1)");
gradientFill.addColorStop(0.5, "rgba(255, 235, 59, 1)");
gradientFill.addColorStop(0.6, "rgba(76, 175, 80, 1)");
gradientFill.addColorStop(0.8, "rgba(33, 150, 243, 1)");
gradientFill.addColorStop(1, "rgba(103, 58, 183, 1)");

The createLinearGradient(x0, y0, x1, y1) method creates a linear gradient object. It has four parameters: (x0,y0), the coordinates of the start point of the gradient and (x1,y1), the coordinates for the end point.

We use (0,0) for the start point, as the graph starts at the top and (0,300), as the graph finishes at the height of its canvas (That’s why used height=300 in the canvas tag)

The addColorStop(stop, colour) method specifies the colours and their position (0–1) in the gradient object.

Formatting the data

We currently have JSONs for both our data sets, but we need to map it to the following arrays:

var labels = dataSet1.map(function(item) {
return item["position"];
});
var data1 = dataSet1.map(function(item) {
return item["height"];
});
var data2 = dataSet1.map(function(item) {
return item["height"];
});

Creating the cat image for the last data point

Use new Image() to create a new object and set its src to the link of your image.

var cat = new Image();
cat.src =
"https://vignette3.wikia.nocookie.net/nine/images/d/dc/Nyancat.png/revision/latest?cb=20120317044335";

Plugins are a way to modify a chart as it is being created. We’ll use the following plugin to set our cat object as the image of our last data point (that’s why we have data[7]).

Chart.pluginService.register({
afterUpdate: function(chart) {
chart.config.data.datasets[0]._meta[0].data[7]._model.pointStyle = cat;
}
});

Creating the chart

We now need to add all the details defined above to our chart:

var myChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [
{
borderColor: gradientStroke,
pointBorderColor: gradientStroke,
pointBackgroundColor: gradientStroke,
pointHoverBackgroundColor: gradientStroke,
pointHoverBorderColor: gradientStroke,
pointBorderWidth: 8,
pointHoverRadius: 8,
pointHoverBorderWidth: 1,
pointRadius: 3,
fill: true,
backgroundColor: gradientFill,
borderWidth: 4,
data: data1
}
]
},
options: {
scaleShowLabels: false,
responsive: true,
maintainAspectRatio: false,
legend: {
position: "none"
},
scales: {
yAxes: [
{
position: "right",
ticks: {
fontColor: "#303F9F",
beginAtZero: true,
maxTicksLimit: 1,
padding: 100
},
gridLines: {
drawTicks: false,
display: false,
drawBorder: false
}
}
],
xAxes: [
{
ticks: {
display: false
},
gridLines: {
zeroLineColor: "transparent"
},
gridLines: {
drawTicks: false,
display: false,
drawBorder: false
}
}
]
}
}
});

At this point, we’ll be able to see the static chart:

Animating the graph

One way to animate the graph is to alternate between the two defined datasets indefinitely.

Let’s start by transitioning from one data set to another with the following code:

var i = 1;function changeDataSets() {
if (i % 2 == 0) {
myChart.data.datasets[0].data = data1;
} else {
myChart.data.datasets[0].data = data2;
}
i++;
myChart.update();
}

The update() function updates chart to use the new dataset.

To call this function continuously, we’ll set an interval that calls the changeDataSets() function every 500ms:

setInterval(function() {
changeDataSets();
}, 500);

… and finally the last touch: the blinking stars

Michał Budzyński created and animated the Nyan cat using pure CSS for a Mozilla Demo Party.

I used the code of the stars from his original work.

As Michał mentioned earlier, the blinking stars are not trivial! We will therefore not cover them in this tutorial, but you can see the code in the live demo in codepen or jsfiddle.

The final result

I hope you enjoyed this tutorial ❤.

If you have any questions, please use the comments section below.

Thanks!

About the author

I’m Valeria and I am passionate about data discovery via beautiful visualisations and analytics. I hope you enjoyed this post!

You can find me on Twitter and Instagram, or visit my page at valeria.io.

Data Scientist at Monzo Bank || Prev. Lloyds Banking Group working on Responsible AI || Advocate for ethical AI and diversity in tech || T: @ValeriaCortezVD