将FontAwesome图标添加到D3graphics

我想设置一个FontAwesome的图标,而不是我的D3节点中的文本。 这是最初的印象,用文字:

g.append('svg:text') .attr('x', 0) .attr('y', 4) .attr('class', 'id') .text(function(d) { return d.label; }); 

现在我尝试使用图标:

 g.append('svg:i') .attr('x', 0) .attr('y', 4) .attr('class', 'id icon-fixed-width icon-user'); 

但是,这不起作用,即使标记是正确的,CSS规则正确命中:图标不可见。

任何想法为什么?

这里是相关的jsbin

编辑

我find了插入图像的替代方法: 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); 

这正是我想要做的,但它不适用于FontAwesome使用的元素。

您需要在正常的文本元素内使用正确的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' }); 

这个确切的代码将呈现一个“图标微笑”图标。 所有的FontAwesome图标的Unicode可以在这里find:

http://fortawesome.github.io/Font-Awesome/cheatsheet/

请注意,您需要将的代码从HTML / CSS unicode格式调整为Javascript unicode格式,以便 必须在您的javascript中写入\uf118

感谢所有的答复。 我的最终解决scheme是基于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]; }); 

小心你的CSS:它优先于SVG属性。

这就是它的样子:

节点图

foreignObject解决scheme相比,这件事情的foreignObject是事件能够被D3妥善处理。

我真的是新的d3,但字体真棒工程通过一个类属性<i>元素的样式。

我发现的唯一方法是附加一个foreignObject并在其上设置字体真棒所需的相关HTML。

参考:

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject?redirectlocale=en-US&redirectslug=SVG%2FElement%2FforeignObject

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>'); 

演示: http : //jsbin.com/eFAZABe/3/

我知道这个问题很老,已经解决了,但是 – 这对我今天是有效的。

从这个网站

 svg.append('svg:foreignObject') .attr("width", 50) .attr("height", 50) .append("xhtml:body") .html('<i class="fa fa-user"></i>'); 

但是对于我的图表,我放弃了附加的xhtml:body ,否则不会让我设置x和y坐标。

元素将采用您设置的字体的宽度和高度。

 d3.select('svg') .append('svg:foreignObject') .attr('class', 'handle') .attr('x', +getLeftBarPosition(i+1, 'handle')[0] + +getLeftBarPosition(i+1, 'handle')[1]) .attr('y', state.barHeight/2) .html('<i class="fa fa-user"></i>') 

只需要在这里input代码,基于CarlesAndres的回答和mhd的​​评论,对我有用:

 node.append("text") .attr("style","font-family:FontAwesome;") .attr('font-size', "50px" ) .attr("x", 440) .attr("y", 440) .text(function(d) { return '\uf118' });