2013-02-20 28 views
47

我有包括图像的SVG:如何在我的svg中包含字体棒图标?

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

如何更换线W /字体真棒图标:

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

似乎并没有工作,因为图像不显示向上。

+0

你需要获得glyp hs元素来自svg。 – David 2013-02-20 15:47:43

回答

87

i是无效的SVG。您需要包含显示图标的实际字符。如果您在font awesome's stylesheet看看你会看到...

.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"; } 

但那些编码对CSS的Unicode字符。在SVG,你将需要例如\f040的语法更改为:

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

然后在你的样式表添加:

svg text { 
    font-family: FontAwesome; 
} 
+0

作品完美。谢谢! – 2013-02-20 17:59:06

+0

@Duopixel如果svg是网站的一部分,FontAwesome(css)被加载,这个解决方案才有效,对吧?有没有办法将单个字体包含到“独立”svg文件中?这个文件应该是可读的“离线”,而不需要从web服务器加载css文件。像一个包:svg和FontAwesome定义到一个svg文件中。 – 2013-08-13 12:38:24

+1

要使用嵌入字体的独立SVG,您需要将字体作为数据嵌入,如果需要详细信息,请打开一个新问题。 – Duopixel 2013-08-13 15:39:00

13

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'; }); 
+0

感谢函数(d){return'\ uf083'; },花了我一段时间来找到这个解决方案。 – NPC 2016-05-03 21:19:01

+0

当我尝试使用window.btoa保存此svg时出现错误**未捕获DOMException:未能在'Window'上执行'btoa':要编码的字符串包含Latin1范围之外的字符。(...)* * – Jerry 2016-12-07 11:00:53

+0

谢谢,但我想知道使用HTML实体和D3js'text'函数将字符串添加到HTML元素的区别?像'\ uf083'和&#xf083 – Allen 2017-05-20 03:48:06