I. nature of icons
Font awesome icon is a font, and its technical term is Icon Font. In essence, it is a character encoded with PUA (Private Unicode Area) code point Unicode. Therefore, the icons of font awesome icon and Bootstrap are the same as those of Wingdings font, and the difference is nothing but encoding.
II. Drawing pictures
After understanding the essence of icon, there is a way to turn icon into text. You can easily get pictures by drawing text on canvas.
1. First, create an html template to attract font awesome
<html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.css"/> </head> <body> <i class="fa fa-address-book"></i> <canvas id="canvas"></canvas> </body> <script src="index.js" type="text/javascript" charset="utf-8"></script> </html>
2. Get the icon and draw it on canvas
//Get the byte code of the icon const icon = document.getElementsByClassName("fa-address-book"); const character = window.getComputedStyle(icon[0],":before").getPropertyValue('content').replace(/\"/g,""); //Drawing icons on canvas const canvas2 = document.getElementById("canvas"); canvas2.width = 200; canvas2.height = 500; const ctx2 = canvas2.getContext("2d"); ctx2.fillStyle = "#000000"; ctx2.font = "24px FontAwesome"; ctx2.textAlign = "center"; ctx2.textBaseline = "middle"; ctx2.fillText(character, 50, 100); //Get pictures in base64 encoding format const dataURL = canvas.toDataURL("image/png"); document.getElementsByTagName("img")[0].setAttribute("src",dataURL);
III. Application Extension
After understanding the principle, we can carry out many application operations. For example, change the cursor style
//Create an icon dom element and remove the icon dom element after getting the byte code of the icon const icon = "fa fa-address-card-o"; const tempElement = document.createElement("i"); tempElement.className = icon; document.body.appendChild(tempElement); const character = window.getComputedStyle(document.querySelector('.fa-address-card-o'), ':before').getPropertyValue( 'content').replace(/\"/g, ""); tempElement.remove(); //Create a canvas element var canvas = document.createElement("canvas"); canvas.width = 24; canvas.height = 24; var ctx = canvas.getContext("2d"); ctx.fillStyle = "#000000"; ctx.font = "24px FontAwesome"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(character, 12, 12); const dataURL = canvas.toDataURL('image/png'); canvas.remove(); //Change cursor style document.querySelector('body').style.cssText = "cursor:url(" + dataURL + "),auto";