简体   繁体   中英

Displaying fontawesome icons inside svg

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?

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>

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;
})();
  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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM