如何在 svg 中包含一个字体很棒的图标?

我有一个 svg,其中包括图像:

<g><image id="myImage" class="myClass" x="12" y="15" width="10" height="10" xlink:href="/images/pic.png"/></g>

如何替换这一行的字体图标:

<g><i class="icon icon-cloud-download" x="12" y="15" width="10" height="10"></i></g>

因为图像没有显示出来,所以看起来不起作用。

63957 次浏览

i is not valid SVG. You need to include the actual character that displays the icon. If you take a look at font awesome's stylesheet you will see...

.icon-group:before                { content: "\f0c0"; }
.icon-link:before                 { content: "\f0c1"; }
.icon-cloud:before                { content: "\f0c2"; }
.icon-beaker:before               { content: "\f0c3"; }
.icon-cut:before                  { content: "\f0c4"; }
.icon-copy:before                 { content: "\f0c5"; }
.icon-paper-clip:before           { content: "\f0c6"; }
.icon-save:before                 { content: "\f0c7"; }
.icon-sign-blank:before           { content: "\f0c8"; }
.icon-reorder:before              { content: "\f0c9"; }
.icon-list-ul:before              { content: "\f0ca"; }
.icon-list-ol:before              { content: "\f0cb"; }
.icon-strikethrough:before        { content: "\f0cc"; }
.icon-underline:before            { content: "\f0cd"; }
.icon-table:before                { content: "\f0ce"; }

But those are unicode characters encoded for CSS. In SVG you would need to change the syntax of example \f040 to:

<g><text x="0" y="0">&#xf040;</text></g>

And then in your stylesheet add:

svg text {
font-family: FontAwesome;
}

According to Niek's comment, if you use the free version of Font Awesome 5+, you must use the following font-family declaration:

svg text {
font-family: 'Font Awesome 5 Free';
}

my Demo

<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div title="Code: 0xe800" class="the-icons span3">


<H3>Standard using:</H3>
<i class="fa fa-camera-retro fa-4x"></i>
<br>
<H3>SVG using:</H3>
</body>
</html>

JS

var svg = d3.select("body")
.append("svg")
.attr("width", 250)
.attr("height", 250);


svg.append("text")
.attr("x",0)
.attr("y",70)
.attr("font-family","FontAwesome")
.attr('font-size', function(d) { return '70px';} )
.text(function(d) { return '\uf083'; });

The below code works for me perfectly.

   svg.append('tspan')
.attr('class', 'fa')
.text('\uf05a')