3

I have a problem with using FontAwesome icons in my HTML 5 canvas, I tried this:

ct.fillStyle = "black";
ct.font = "20px Font Awesome";
ct.textAlign = "center";

var h = 'F1E2';

ct.fillText(String.fromCharCode(parseInt(h, 16)), x, y);

I tried importing the FontAwesome CSS file but it didn't work! Can anybody help me with this?

Thanks!

JoshG
  • 6,472
  • 2
  • 38
  • 61
Gobli gaming
  • 39
  • 1
  • 6
  • did you download it on your machine or you tried accessing it online? locally: https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself; online: https://fontawesome.com/start – mdln97 Feb 10 '19 at 11:05

1 Answers1

5
  • First, if you're using FA5, use Font Awesome 5 Free. If you're using FA4, you can just use FontAwesome.
  • You need to set the font-weight to a high value (like 600).

Example:

var ctx = canvas.getContext("2d");
document.fonts.ready.then(_ => {
  ctx.font = '600 48px "Font Awesome 5 Free"';
  ctx.fillStyle = "black";
  setTimeout(_ => ctx.fillText("\uF200", 45, 45), 200);
});
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
canvas {
  font-family: 'Font Awesome 5 Free';
  font-weight: 600;
}
<canvas id="canvas"></canvas>
JoshG
  • 6,472
  • 2
  • 38
  • 61
  • Isn't FA Free font-weight: 900? – zer00ne Feb 10 '19 at 11:44
  • @zer00ne For the solid style, the `font-weight` needs to be in the range 600-900 (basically, anything in the semi-bold to heavy range). For example, if you replace the "600" in my snippet with `bold`, it should still render the icon. I believe the examples tend to use 900 because that's the largest possible value for `font-weight` in the CSS spec. But as long as you use a value in the 600-900 range, I believe it should work for FA5 Free. – JoshG Feb 10 '19 at 12:32
  • @zer00ne And actually, here's another answer that corroborates that: https://stackoverflow.com/a/49755090 – JoshG Feb 10 '19 at 12:32
  • @AndroidNoobie thanks that's good to know. I always thought 900 was ridiculous but never really saw any difference. – zer00ne Feb 10 '19 at 12:47
  • But what if we want to load different class like fas, far, fab? I cant find any solution online – Neo Jun 21 '21 at 07:25
  • 1
    @Neo `far` (Font Awesome Regular) requires a [pro subscription](https://fontawesome.com/pro). If you're using the Pro version, just change the `font-family` above to `Font Awesome 5 Pro`. – JoshG Jun 21 '21 at 13:06
  • Yea, stupidly I just found out, I just need to simply change to "Font Awesome 5 Brands" or Pro or others. I spent few days looking for it. Thanks anyway! – Neo Jun 22 '21 at 06:35