16

How can I draw Font Awesome characters (Icons Glyphs) onto html5 canvas? I am using an older version of Font Awesome.

How can I style those drawn characters?

<script>

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    context.font = '';
    context.fillText();

</script>

language: lang-html

<canvas id="myCanvas" class="canvas" width="500" height="500" ></canvas>html>

<script>

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    context.font = '';
    context.fillText();

</script>

language: lang-html

<canvas id="myCanvas" class="canvas" width="500" height="500" ></canvas>
T.Woody
  • 1,142
  • 2
  • 11
  • 25
Kanishk Pipariya
  • 179
  • 1
  • 2
  • 8

2 Answers2

40

enter image description here

Here's how to draw Font Awsome glyphs on html5 canvas:

  1. Link in Font Awesome:

    <link rel="stylesheet" 
        href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    
  2. Set the context font to Font Awesome:

    // set the canvas context's font-size and font-face
    context.font='14px FontAwesome';
    
  3. Draw one of the Font Awesome characters on the canvas:

    // specify the desired character code with the Unicode prefix (\u) 
    context.fillText('\uF047',20,50);
    

Here's example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

ctx.font='12px verdana';
ctx.fillText('Please wait for Font Awesome to load...',20,30);

// give font awesome time to load
setTimeout(start,2000);

function start(){
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.font='30px FontAwesome';
  ctx.fillText('\uF047',20,50);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<h4>Font Awesome glyph drawn onto html5 canvas</h4>
<canvas id="canvas" width=300 height=100></canvas>

[Addition: another way to load FontAwesome]

And as @Kaiido comments, you can cause the browser to start loading FontAwesome by setting the font-family:fontawesome on the canvas element (or another element).

The demo shows how to load custom fonts (including FontAwesome) "on-the-fly".

[Addition: A FontAwesome onload function]

Like img's, fonts load asynchronously so you must wait for them to fully load before trying to draw with them on canvas. But unlike imgs, fonts don't have a built-in .onload method to tell us when they are fully loaded.

Here's a workaround onload function you can use to trigger a callback when FontAwesome has fully loaded and is ready to fillText on the canvas:

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red; margin:0 auto; }
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw,ch;

    AwesomeFontOnload(start,3000);

    function start(){
        ctx.font='48px fontawesome';
        ctx.fillText('\uF064\uF065 \uF0a5',20,75);
    }

    function AwesomeFontOnload(callback,failAfterMS){
        var c=document.createElement("canvas");
        var cctx=c.getContext("2d");
        var ccw,cch;
        var fontsize=36;
        var testCharacter='\uF047';
        ccw=c.width=fontsize*1.5;
        cch=c.height=fontsize*1.5;
        cctx.font=fontsize+'px fontawesome';
        cctx.textAlign='center';
        cctx.textBaseline='middle';
        var startCount=pixcount();
        var t1=performance.now();
        var failtime=t1+failAfterMS;
        //
        requestAnimationFrame(fontOnload);
        //
        function fontOnload(time){
            var currentCount=pixcount();
            if(time>failtime){
                alert('Font Awsome failed to load after '+failAfterMS+'ms.');
            }else if(currentCount==startCount){
                requestAnimationFrame(fontOnload);
            }else{
                callback();
            }
        }
        //
        function pixcount(){
            cctx.clearRect(0,0,ccw,cch);
            cctx.fillText(testCharacter,ccw/2,cch/2);
            var data=cctx.getImageData(0,0,ccw,cch).data;
            var count=0;
            for(var i=3;i<data.length;i+=4){
                if(data[i]>10){count++;}
            }
            return(count);
        }
    }

}); // end $(function(){});
</script>
</head>
<body>
    <h4>Font Awesome glyphs drawn onto html5 canvas</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
markE
  • 102,905
  • 11
  • 164
  • 176
  • 1
    I would +1, but you actually need to set the `font-family : fontAwesome` on any element in css (even on the canvas) so the browser do load the fonts. – Kaiido Feb 23 '16 at 13:52
  • @Kaiido. Actually, setting a `font-family` is not *required*. With canvas you can use context.font to load one or more(!) custom fonts for use with context.fillText -- including FontAwesome plus other custom fonts. The demo works fine without committing the canvas element to any particular font family, but it does require the awkward `setTimeout` to give the custom font time to load. And yes, if you just need just the one custom font then you could add `font-family='fontawesome'` to the canvas. Thanks for mentioning the alternative -- I'll add your comment to my answer! :-) – markE Feb 23 '16 at 17:40
  • I m far from my computer now so it's hard to find the proper links but I think most browsers need to get an element using a font to actually load a fontface. From my experience, the context's declaration isn't enough (or I may never have waited enough after it) to get the font face loaded. Your snippet didn't worked on my Mac (neither on chrome nor on FF)hence the comment – Kaiido Feb 23 '16 at 23:01
  • 1
    That last edit definitely works ! awesome job. So canvas does trigger the font-face loading ; as I thought, I never did wait enough before running ctx.fillText. Some links I did read about it before this question : http://stackoverflow.com/a/4712339/3702797 http://stackoverflow.com/questions/5680013/how-to-be-notified-once-a-web-font-has-loaded – Kaiido Feb 24 '16 at 07:11
  • 3
    Sows square for me too. I needed to do ctx.fillText(String.fromCharCode("0xf03d"), 20, 75) for i to work – Nitzan Wilnai Feb 28 '18 at 07:03
  • 2
    To get this working, I had to use ctx.font="bold 20px 'Font Awesome 5 Free'". I got fa 5.8.1 from a webjar and it included a not-bold font file with a very limited subset of icons. – Stomf Nov 21 '19 at 10:21
4

how to use font icons (Font Awesome) in html canvas

you can inspect the fontawsome .css file and get what code has been used for each icon.

For Eg: If you see the file for the code used to get the icon fa-info-circle, its as below

.fa-info-circle:before {
  content: "\f05a";
}

So try context.font = '\uf05a'; // this will give you fa-info-circle. And remember to add the \u before the code. Also you need to mention the font family as FontAWsome

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
  • I am not setting the font in css. I just showed him the css code used for a icon inside fontawsome.css file. He just needs to use it in his context, Also I have mentioned the `context.font` in the answer. – Rajshekar Reddy Feb 23 '16 at 07:13