delavnog delavnog - 1 year ago 130
Javascript Question

Adding FontAwesome icons to a D3 graph

I am trying to set an icon with FontAwesome instead of text in my D3 nodes. This is the original implmentation, with text:

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

And now I try with icons:

.attr('x', 0)
.attr('y', 4)
.attr('class', 'id icon-fixed-width icon-user');

But this is not working, even though the markup is right, and the CSS rules are properly hit: the icons are not visible.

Any idea why?

Here is the related jsbin


I have found this alternative to insert images:

.attr("xlink:href", "")
.attr("x", -8)
.attr("y", -8)
.attr("width", 16)
.attr("height", 16);

Which is exactly what I want to do, but it does not work with
elements used by FontAwesome.


You need to use the proper Unicode inside a normal text element, and then set the font-family to "FontAwesome" like this:

    .attr('font-family', 'FontAwesome')
    .attr('font-size', function(d) { return d.size+'em'} )
    .text(function(d) { return '\uf118' }); 

This exact code will render an "icon-smile" icon. The unicodes for all FontAwesome icons can be found here:

Be aware that you need to adapt the codes in the cheatsheet from HTML/CSS unicode format to Javascript unicode format so that &#xf118; must be written \uf118 in your javascript.