Today, I wanted to be able to use FontAwesome to display nice icons in a Chart.JS.

As you might know, Chart.JS renders its output through a HTML 5 Canvas, which allow very good results but can be sometimes a bit more complex. To be able to use FontAwesome, in fact, it’s pretty easy because you just need to instruct the canvas to draw some text using the custom font:

const canvas = (<HTMLCanvasElement>document.getElementById(this.chartId));
const ctx = canvas.getContext('2d');

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = '14px "FontAwesome"';
ctx.fillText('\uf72e', 10, 10);

Unfortunately, if you follow the previous code, you will see that, sometimes, the text is not correctly displayed and you only see a square with borders. After doing some experiments, I’ve found that you need to change the font weight (and to put it to precisely 900) to be able to display the text correctly so, something like that:

ctx.font = '900 14px "FontAwesome"';

Using this code, your text can be correctly rendered in your Canvas:

This is a simple trick, maybe needed because I’m not used to use that components but I thought it could be useful to someone else 😉

Happy coding!


How to remove tick marks in Chart.JS Using Azure Blob Storage to host static files

Leave a Reply

Your email address will not be published. Required fields are marked *