一、图标的本质
font-awesome图标是字体,专业术语叫 Icon Font,本质上是使用 PUA ( Private Unicode Area )码位 Unicode 编码的字符,所以font-awesome图标、Bootstrap 的图标和 Wingdings 字体都是一样的,不一样的无非是编码。
二、绘制图片
理解了图标的本质,那图标转成文本就有了一个思路,把文本绘制到canvas上,就可以轻松获取到图片了
1.首先,创建一个html模板,引人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.获取到图标,并绘制到canvas上
//获取图标的字节编码
const icon = document.getElementsByClassName("fa-address-book");
const character =
window.getComputedStyle(icon[0],":before").getPropertyValue('content').replace(/\"/g,"");
//在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);
//获取图片base64编码格式的图片
const dataURL = canvas.toDataURL("image/png");
document.getElementsByTagName("img")[0].setAttribute("src",dataURL);
三、应用扩展
理解原理后,我们就可以进行很多应用操作,这里举个例子,更换光标样式
//创建一个图标dom元素,获取到图标的字节编码后移除图标dom元素
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();
//创建一个canvas元素
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();
//更改光标样式
document.querySelector('body').style.cssText = "cursor:url(" + dataURL + "),auto";