首页 > 解决方案 > 无法将字体加载到画布

问题描述

我无法加载要在画布中使用的字体。我OpenSans-Regular.ttf在与 html 相同的文件夹中有字体文件。

<style>
@font-face {
    font-family: 'OpenSans';
    src: url(OpenSans-Regular.ttf) format("truetype");
}
</style>

<canvas id="c" width="1000" height="1400"></canvas>


<script>

var c = document.getElementById("c").getContext('2d');

c.font = '100px OpenSans';
c.fillText('Loading...', 110, 110);

</script>

这确实加载了字体(在调试器/网络中),但不在画布上使用。如果我src: url(OpenSans-Regular.ttf)local('OpenSans-Regular.ttf')它替换它甚至不会加载到调试器/网络中。我尝试以两种方式添加/删除引号,尝试删除和添加.ttf。但没有任何效果。

注意:我在其中一些尝试中确定字体已正确加载,并且可以在其他元素中使用它。

谢谢

标签: htmlcssfonts

解决方案


如果您在调试器中看到字体文件,则您的画布代码可能在字体加载之前正在运行。

您可以在此答案中阅读更多关于 Daniel White 提到的可能重复的问题:https ://stackoverflow.com/a/7289880/864799

除了 WebFontLoader,您可能希望使用同一维护者更新的FontFaceObserver 。

例如:

<style>
@font-face {
    font-family: 'Example';
    src: url('Example-Regular.woff2') format('woff2');
}
</style>

<canvas id="c" width="1000" height="1400"></canvas>

<!-- You could also include this locally, but this is the latest version at the time of writing. -->
<script src="https://unpkg.com/fontfaceobserver@2.1.0/fontfaceobserver.standalone.js"></script>
<script>

var c = document.getElementById("c").getContext('2d');

var font = new FontFaceObserver('Example', {
  weight: 400
});

font.load().then(function () {
  console.log('Font is available');

  c.font = '100px Example';
  c.fillText('Loading...', 110, 110);  

}, function () {
  console.log('Font is not available');
});
</script>

您可以在FontFaceObserver README中找到更详细的示例。


推荐阅读