How to Add Font-Awesome Icons to SVG based D3.js Graphs?

Font-Awesome is a popular fonts on-line. Including font styles font-awesome provides various salable vector icons. These icons are easily customization. We can add any colors & size to these icons. Performance wise it is more better to use font-family based icons rather then an icon image file. In the below example I am showing the trick How to use font-awesome icon in a SVG graph.

In this example I referred the CDN link of font-awesome.css. Using D3.js here I am appending SVG to my div with id “d3svg”. To add font-awesome user icon (fa-user) in SVG we need to append foreignObject to our svg element. Here I did this using “svg.append('svg:foreignObject')“. To set the attributes to this foreignObject I used .attr(key, value). To implement an icon <i> tag is must required. In this cause I added .html('<i class="fa fa-user"></i>');.

fa-user is the class for User icon. To implement fa-user you need to write “fa fa-user”. Here fa acts like the parent class. To run the below example you just need to copy the codes to a notepad file & save it as html. Open it you can see the demo.

How to add Font-Awesome Icons?

<title>How to add font-awesome icons to SVG?</title>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22http%3A%2F%2Fd3js.org%2Fd3.v3.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
 	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<div id="d3svg"></div>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%3Cwp-br%20%2F%3E%0A%2F*%20Appening%20svg%20to%20topology%20Div%20*%2F%3Cwp-br%20%2F%3E%0Avar%20svg%20%3D%20d3.select(%22%23d3svg%22)%3Cwp-br%20%2F%3E%0A.append(%22svg%22)%3Cwp-br%20%2F%3E%0A.attr(%22width%22%2C%20%22100%25%22)%3Cwp-br%20%2F%3E%0A.attr(%22height%22%2C%20%22500px%22)%3C%2Fcode%3E%3C%2Fspan%3E%3C%2Fwp-p%3E%0A%3Cwp-p%3E%3Cspan%20style%3D%22color%3Abrown%22%3E%3Ccode%3Esvg.append('svg%3AforeignObject')%3Cwp-br%20%2F%3E%0A.attr(%22width%22%2C%2050)%3Cwp-br%20%2F%3E%0A.attr(%22height%22%2C%2050)%3Cwp-br%20%2F%3E%0A.append(%22xhtml%3Abody%22)%3Cwp-br%20%2F%3E%0A.html('%3Ci%20class%3D%22fa%20fa-user%22%3E%3C%2Fi%3E')%3B%3Cwp-br%20%2F%3E%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />