dan*_*ast 50 javascript d3.js font-awesome
我试图在我的D3节点中使用FontAwesome而不是文本设置一个图标.这是原始的implmentation,带有文字:
g.append('svg:text')
.attr('x', 0)
.attr('y', 4)
.attr('class', 'id')
.text(function(d) { return d.label; });
Run Code Online (Sandbox Code Playgroud)
现在我尝试使用图标:
g.append('svg:i')
.attr('x', 0)
.attr('y', 4)
.attr('class', 'id icon-fixed-width icon-user');
Run Code Online (Sandbox Code Playgroud)
但是这不起作用,即使标记是正确的,并且CSS规则被正确命中:图标不可见.
知道为什么吗?
这是相关的jsbin
我找到了插入图像的替代方法:http://bl.ocks.org/mbostock/950642
node.append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("x", -8)
.attr("y", -8)
.attr("width", 16)
.attr("height", 16);
Run Code Online (Sandbox Code Playgroud)
这正是我想要做的,但它不适<i>用于FontAwesome使用的元素.
Car*_*res 83
您需要在普通文本元素中使用正确的Unicode,然后将font-family设置为"FontAwesome",如下所示:
node.append('text')
.attr('font-family', 'FontAwesome')
.attr('font-size', function(d) { return d.size+'em'} )
.text(function(d) { return '\uf118' });
Run Code Online (Sandbox Code Playgroud)
这个确切的代码将呈现一个"图标微笑"图标.可以在此处找到所有FontAwesome图标的unicodes:
http://fortawesome.github.io/Font-Awesome/cheatsheet/
请注意,您需要将备忘单中的代码从HTML/CSS unicode格式调整为Javascript unicode格式,以便必须\uf118在您的javascript中编写.
dan*_*ast 33
感谢所有回复.我的最终解决方案是基于CarlesAndres的答案:
g.append('text')
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'central')
.attr('font-family', 'FontAwesome')
.attr('font-size', '20px')
.text(function(d) { return ICON_UNICODE[d.nodeType]; });
Run Code Online (Sandbox Code Playgroud)
小心你的CSS:它优先于SVG属性.
这就是它的样子:

与foreignObject解决方案相比,这方面的好处是事件由D3正确处理.
我是d3的新手,但字体很棒,通过<i>使用class属性设置元素样式.
我找到的唯一方法是在其上添加foreignObject并设置字体真棒所需的相关HTML.
参考:
http://fortawesome.github.io/Font-Awesome/examples/
码:
g.append('svg:foreignObject')
.attr("width", 100)
.attr("height", 100)
.append("xhtml:body")
.html('<i class="icon-fixed-width icon-user"></i>');
Run Code Online (Sandbox Code Playgroud)
演示:http://jsbin.com/eFAZABe/3/
鉴于其他答案不再起作用(因为d3js已同时进行了更新),并且由于兼容性问题,它不是一个很好的解决方案svg:foreignObject,因此以下答案无需使用任何技巧即可起作用:
.append("text") // Append a text element
.attr("class", "fa") // Give it the font-awesome class
.text("\uf005"); // Specify your icon in unicode (https://fontawesome.com/cheatsheet)
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例(单击“运行代码段”,d3代码输出三颗星):
var icons = [1, 2, 3];
d3.select("body")
.selectAll(".text")
.data(icons)
.enter()
.append("text") // Append a text element
.attr("class", "fa") // Give it the font-awesome class
.text("\uf005"); // Specify your icon in unicodeRun Code Online (Sandbox Code Playgroud)
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)