javascript - 如何在 Canvas 中绘制 fontawesome(version >=5.0)?

标签 javascript css canvas unicode font-awesome

我想在 Canvas 上绘制精美的图标。

下面是我的代码:

<canvas id="canvas" width="400" height="400" style="border:1px solid #d3d3d3;"></canvas>

<script>
    var content = '\uF006';
    var context = document.getElementById('canvas').getContext('2d');
    context.font = '48px Material Design Icons';
    context.fillText(content, 100, 100);
    context.strokeText(content, 100, 100);
</script>

我已经导入了字体文件并链接了它。但它不起作用: it just show a rectangle which is empty.

你能告诉我为什么吗?

一件有趣的事情是,当我链接 fontawesome 4.5 版在线地址时它可以工作:enter link description here

两个版本有什么区别?

最佳答案

除了@TanDuong 的正确声明之外,您似乎甚至需要将字体粗细设置为 900 才能让字体生效...

另请注意 Chrome 76+现在要求字体为 explicitly loaded ,或者文档中存在使用该字体的字符之一(不再可能通过 CSS 仅针对 Canvas )。

const ctx = c.getContext("2d");
const font = '900 48px "Font Awesome 5 Free"';
// Chrome 76+ won't load the font
// until it's needed by the ducument (i.e one of the characters is displayed)
// or explicitely loaded through FontFaceSet API.
document.fonts.load(font).then((_) => {
  ctx.font = font;
  ctx.fillStyle = "red";
  // note that I wasn't able to find \uF006 defined in the provided CSS
  // falling back to fa-bug for demo
  ctx.fillText("\uF188", 50, 50);
})
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
<canvas id="c"></canvas>

关于javascript - 如何在 Canvas 中绘制 fontawesome(version >=5.0)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49728830/

相关文章:

javascript - 将文本拆分为页面并单独呈现 (HTML5)

javascript - 将获取的 JSON 保存到变量中

javascript - Bootstrap,内联输入在动态添加时具有更小的间隙

html - CSS border-radius 属性不起作用

html - 缩放图像并将它们 float 成一行

javascript - 如何在特定数据标签上隐藏 Chart.js 中的工具提示?

javascript - Slack 和 Hipchat 使用什么技术栈?

javascript - Google Blogger 剥离 <p> 标签,需要一种方法来对每个节的开头进行文本缩进

c# - 在 WPF 程序中,我想更改 "Lines"上所有 "Canvas"的描边颜色

python - 如何将条目小部件中输入的值打印到 Canvas 中