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

烂漫一生 提交于 2019-12-14 01:00:26

问题


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?


回答1:


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>



回答2:


In Font Awesome 5. You should use

context.font = '48px Font Awesome 5 Free'

In Font Awesome 4. You should use

context.font = '48px FontAwesome'

This is defined on FontAwesome. You can search @font-face to see what font name defined in Font Awesome 5




回答3:


Finally, I add a webfontloader.js, which makes it work perfect!

    <script src="./webfontloader.js"></script>

the webfontloader.js file can be found on the web.



来源:https://stackoverflow.com/questions/49728830/how-to-draw-fontawesomeversion-5-0-in-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!