Search code examples
javascriptjquerycanvasfont-awesomefont-awesome-5

How to get a Font Awesome 5 icon as cursor


In Font Awesome 4x I managed to set the cursor as an icon by changing it into a base-64 image url. Now in Font Awesome 5 it does not work any more.

I've found this solution, but it's not working here.

This is what I've tried.

var canvas = document.createElement("canvas");
canvas.width = 20;
canvas.height = 20;
var ctx = canvas.getContext("2d");
document.fonts.ready.then(function() {
    ctx.font = "400 20px Font Awesome 5 Pro";
    ctx.fillStyle = "red";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    setTimeout(function() {
        ctx.fillText("\uf2ed", 10, 10)
        var dataURL = canvas.toDataURL('image/png')
        $('#foo').css('cursor', 'url(' + dataURL + '), auto');
    }, 200)
})

All I get is a black square 20x20

Is there anyone who knows how to get it done?


Solution

  • see the below example ...

    var hex = 0xF25A;
    var unicode = String.fromCharCode(parseInt(hex, 16));
    
    var canvas = document.getElementById("cache");
    canvas.width = 64; canvas.height = 64;
    
    var context = canvas.getContext("2d");
    context.font = '900 32px "Font Awesome 5 Free"';
    context.fillText(unicode, canvas.width/2, canvas.width/2);
      
    document.fonts.ready.then(function() {
        $('body').css('cursor', 'url(' + canvas.toDataURL('image/png') + '), auto');
    });
    html, body {height: 100%; width:100%; margin:0; padding: 0;}
    canvas#cache {display: none;}
    <link rel="stylesheet" href="//use.fontawesome.com/releases/v5.2.0/css/solid.css" integrity="sha384-wnAC7ln+XN0UKdcPvJvtqIH3jOjs9pnKnq9qX68ImXvOGz2JuFoEiCjT8jyZQX2z" crossorigin="anonymous">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <canvas id="cache"/>