【发布时间】:2020-12-15 11:36:56
【问题描述】:
我希望能够:
- 为任何给定的 Font Awesome 类名称(
fas fa-check-circle等)获取 Font Awesome 5 unicode 字符 - 将该 Unicode 字符绘制到 html5 画布上
我该怎么做呢?
【问题讨论】:
标签: javascript html5-canvas font-awesome font-face
我希望能够:
fas fa-check-circle 等)获取 Font Awesome 5 unicode 字符我该怎么做呢?
【问题讨论】:
标签: javascript html5-canvas font-awesome font-face
为 Font Awesome 5 图标类获取正确的 unicode 字符和其他重要数据并将其绘制到 html5 画布上:
// create an icon with the Font Awesome class name you want
const i = document.createElement('i');
i.setAttribute('class', 'fas fa-check-circle');
document.body.appendChild(i);
// get the styles for the icon you just made
const iStyles = window.getComputedStyle(i);
const iBeforeStyles = window.getComputedStyle(i, ':before');
const fontFamily = iStyles.getPropertyValue('font-family');
const fontWeight = iStyles.getPropertyValue('font-weight');
const fontSize = '40px'; // just to make things a little bigger...
const canvasFont = `${fontWeight} ${fontSize} ${fontFamily}`; // should be something like: '900 40px "Font Awesome 5 Pro"'
const icon = String.fromCodePoint(iBeforeStyles.getPropertyValue('content').codePointAt(1)); // codePointAt(1) because the first character is a double quote
const ctx = myCanvas.getContext('2d');
ctx.font = canvasFont;
ctx.fillStyle = 'red';
ctx.textAlign = 'center';
ctx.fillText(icon, myCanvas.width / 2, myCanvas.height / 2);
执行此操作时,请确保在绘图时实际加载了 Font Awesome 5 字体。我在测试时犯了只画一次的错误,结果只出现了一个框。加载图标后,它应该如下所示:
【讨论】: