Font awesome icon to picture

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

		<meta charset="utf-8">
		<link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.css"/>
        <i class="fa fa-address-book"></i>
		<canvas id="canvas"></canvas>
	<script src="index.js" type="text/javascript" charset="utf-8"></script>

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 = 
	//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");

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;
	const character = window.getComputedStyle(document.querySelector('.fa-address-card-o'), ':before').getPropertyValue(
		'content').replace(/\"/g, "");

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

	//Change cursor style
	document.querySelector('body').style.cssText = "cursor:url(" + dataURL + "),auto";

Keywords: Front-end encoding Javascript

Added by justice1 on Tue, 15 Oct 2019 18:59:49 +0300