How to add font-awesome icons to SVG based D3.js Graphs?

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?

<!DOCTYPE html>
<html>
<head>
<title>How to add font-awesome icons to SVG?</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
</head>
<body>
<div id="d3svg"></div>
<script type="text/javascript">
/* Appening svg to topology Div */
var svg = d3.select("#d3svg")
.append("svg")
.attr("width", "100%")
.attr("height", "500px")</code></span>
<span style="color:brown"><code>svg.append('svg:foreignObject')
.attr("width", 50)
.attr("height", 50)
.append("xhtml:body")
.html('<i class="fa fa-user"></i>');
</script>
</body>
</html>