Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to draw fontawesome(version >=5.0) in canvas?

I want to draw fontawesome icons on the canvas.

Below is my code:

<canvas id="canvas" width="400" height="400" style="border:1px solid #d3d3d3;"></canvas>

<script>
    var content = '\uF006';
    var context = document.getElementById('canvas').getContext('2d');
    context.font = '48px Material Design Icons';
    context.fillText(content, 100, 100);
    context.strokeText(content, 100, 100);
</script>

I have imported the font files and linked it. But it doesn't works: it just show a rectangle which is empty.

can you tell me why?

one interesting thing is that it works when I link the fontawesome version 4.5 online address : enter link description here

where the difference between the two version?

like image 480
katie xia Avatar asked Apr 09 '18 08:04

katie xia


People also ask

How do I use Font Awesome 5?

To use the Free Font Awesome 5 icons, you can choose to download the Font Awesome library, or you can sign up for an account at Font Awesome, and get a code (called KIT CODE) to use when you add Font Awesome to your web page.

How do I change the size of font awesome?

To increase icon sizes relative to their container, use the fa-lg (33% increase), fa-2x , fa-3x , fa-4x , or fa-5x classes. If your icons are getting chopped off on top and bottom, make sure you have sufficient line-height.

Is Fontawesome 6 backwards compatible?

We tested many upgrading-to-v6 scenarios and tweaked our docs accordingly. That means Font Awesome 6 is backward compatible, and upgrading should be straightforward, even directly from version 4.

How do I use Font Awesome 4.7 offline?

Go to font awesome official website and download free zip file, extract it and link this to your page, done..! To be able to use font awesome offline you would have to manually download the icons to your local computer. You should be able to find the required files from the font awesome website.


1 Answers

In addition to @TanDuong correct statement, it seems you even need to set the font-weight to 900 for the font to kick in...

Also note that Chrome 76+ now requires that the font is explicitly loaded, or that one of the characters using the font is present in the document (targeting only the canvas through CSS is not possible anymore).

const ctx = c.getContext("2d");
const font = '900 48px "Font Awesome 5 Free"';
// Chrome 76+ won't load the font
// until it's needed by the ducument (i.e one of the characters is displayed)
// or explicitely loaded through FontFaceSet API.
document.fonts.load(font).then((_) => {
  ctx.font = font;
  ctx.fillStyle = "red";
  // note that I wasn't able to find \uF006 defined in the provided CSS
  // falling back to fa-bug for demo
  ctx.fillText("\uF188", 50, 50);
})
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
<canvas id="c"></canvas>
like image 67
Kaiido Avatar answered Oct 12 '22 23:10

Kaiido