html - 无法将字体加载到画布
问题描述
我无法加载要在画布中使用的字体。我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。但没有任何效果。
注意:我在其中一些尝试中确定字体已正确加载,并且可以在其他元素中使用它。
谢谢
解决方案
如果您在调试器中看到字体文件,则您的画布代码可能在字体加载之前正在运行。
您可以在此答案中阅读更多关于 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中找到更详细的示例。
推荐阅读
- java - Java ClassLoader.getResource(String name) 找到目录但其中没有文件
- apache-kafka - 属性文件中关于 num.partitions 的行为
- ios - 将 RN FFMPEG 集成到本机反应中时出错
- python - 回到主菜单时,诅咒 Python 不清理窗口
- php - 如何在php的第一行之前获得总计/总和
- java - 无法访问 FileChooser 方法
- python - 如果释放,则在按下键时返回true的Python代码为false?
- firebase - 适用于应用的自定义 Firebase API
- c# - 我无法使用 EF core 2.2 加载身份用户
- r - 从复杂表中选择最高对