This post introduces how to draw a heatmap chart using Canvas. By the end of the post, you can get the result as shown in the following image.
A heat map is a graphical representation of data where the individual values contained in a matrix are represented as colors. Fractal maps and tree maps both often use a similar system of color-coding to represent the values taken by a variable in a hierarchy. The term is also used to mean its thematic application as a choropleth map.
From Wikipedia
There are plenty of Heatmap JavaScript libraries. So…
Why Bother Making One?
Well, maybe you would just get curious about it one day, as I did.
Step 1. Preparing a Blurring Brush
The brush will be later used to generate the blending effect.
Create a Canvas
We create a new small Canvas of the brush size. Here, we set the brushSize
to be 10, which is the radius of the distict brush size, while brushBlurSize
is the extra radius of blurring area.
In order to render shadow without the distinct circle, we draw the distinct circle in an invisible place, which is to the left of the canvas in our case. And then, use shadowOffset
to draw shadow in the center of the canvas. The circle is drawn in black, and is blended with other brushes using alpha value and shadow blur.
The brush is shaped as the image in the right shows.
Step 2. Drawing with The Brush
We can generate some random data to see how well our brush works, and may further changing the size of the brush to get a better effect.
And use data
to draw brushCanvas
to a new canvas, we can get the following gray image.
Where is my color?!
Hold on…
Step 3. Preparing a Gradient Map
In order to may different darkness into different color in our heatmap, we need a gradient map as a dictionary. Then, we use the alpha value to determine which color to use in the dictionary.
We create a Canvas of 1 x 256 size, in which 256 is the gradient level.
gradientPixels
is the pixel array of the gradient canvas. Since each pixel contains red, green, blue, and alpha channel, the length of gradientPixels
is 256 * 4, which is 1024.
In order to visualize the gradient map, we set the width a bit wider, as shown in the right image. But remember in gradient
, it’s only of 1 pixel wide.
Step 4. Colorize using Gradient Map
Finally!! :joy:
The canvas is colorized by mapping alpha value to the gradient map.
To make the result nicer, we modify our random data generating method.
And now, the heat map is drawn to your Canvas!
Reference
In fact, I read about 3 to 4 Heatmap Chart libraries and most of them are rendered in this way. simpleheat is a small but powerful implementation among them.