5

How I could display an fontawesome icon inside an svg snipet? I tried with the following but it doesn't work:

<svg xmlns="http://www.w3.org/2000/svg">
<g>
  <rect x="0" y="0" width="100" height="100" fill="red" ></rect>
  <text x="30" y="30" font-family="FontAwesome" font-size="20" fill="blue" >&#xf042;</text>
</g>
</svg>

The unicode &#xf042; corresponds to the fa-adjust icon as can be found here. Also, How I could get the unicode from the icon's name?

bachr
  • 5,780
  • 12
  • 57
  • 92
  • Possible duplicate of [How do I include a font awesome icon in my svg?](https://stackoverflow.com/questions/14984007/how-do-i-include-a-font-awesome-icon-in-my-svg) – Sebbas Sep 04 '18 at 12:15

3 Answers3

6

Your stylesheet should declare the font-family

svg text {
   font-family: FontAwesome;
   font-size:20px;
   background-color:blue;
}

Html

<text x="30" y="30">&#xf042;</text>
4
  1. Add the FontAwesome stylesheet to your page (I used 5.14.10)

  2. set 'fas' (or 'fa') as class of the svg text element.

  3. in the element, provide the character with "&#x" in front in stead of "\" (this example is an arrow-down (fa-var-arrow-down)

See snippet below

<head>  
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
        integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog=="
        crossorigin="anonymous" />
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500">
  <text x="0" y="15" class="fas">&#xf063;</text>
</svg>
</body>
ESDEE
  • 125
  • 7
1

Your code should work, assuming you're including the fontawesome css correctly inside your document. I literally pasted your code into a fiddle and included the latest version of fontawesome via CDN and it worked: http://jsfiddle.net/mayacoda/o59uak50/

For the second part, I'm assuming you want to be able to just type the icon name without having to look up every unicode. Considering I don't know the context for this, I'm also going to assume that you're using javascript and a useable form for this functionality would be an object with key-value pairs (name: "unicode").

You can run this script on the cheatsheet page, it will scan through the elements on the page and return an object with key-value pairs like so:

{
 "fa-adjust": "&#xf042;"
 ...
}

Run the script in the console.

(function () {
    var unicode = {};

    $('.fa').each(function() {
        var code = $(this).siblings().text().match(/\[(.*)\]/);
        code = code ? code[1] : '';

        var name = $(this).parent()[0].innerText.match(/\b(.*)\[/);
        if (!name || !name[1]) {
            return;
        }

        name = name[1].trim();
        unicode[name] = code;
    });

    return unicode;
})();
mayacoda
  • 170
  • 1
  • 10
  • Thanks for pointing to jsfiddle, the code actually works and I just find the problem: it's the `&` that was inserted as `&` !! – bachr May 05 '15 at 08:16