canvas 上的自定义字体仅适用于 safari

Custom font on canvas only working for safari

我目前正在 JavaScript 和 jQuery 中构建一个 canvas 游戏。对于状态栏,我想使用一种名为 "pixelart.ttf" 的自定义字体。在 index.html 我添加了以下内容:

<style type="text/css">
    @font-face {
        font-family: pixelart;
        src: url(misc/pixelart.ttf);
    }
</style>

这是在所有 脚本加载之前。 canvas 也在这个页面上。

这是用字体绘制状态栏的代码:

context.fillStyle = 'rgba(25, 25, 25, 0.1)';
context.textBaseline = 'top';
context.font = fontSize + ' ' + fontName; // will become '25px pixelart'
context.fillText(currentText, 50, 50);

在 Mac 和 iPhone 的 Safari 中,该字体有效,在所有其他浏览器上无效。 当我在 Chrome 或 Firefox 中查看加载的资源时,字体在那里,但它显示另一种默认字体。

我尝试了一些东西。例如在正文顶部添加:

<div style"font-family: pixelart"></div>

但这也行不通。

有什么建议吗?

除了 .ttf 之外,您还需要在 .eot .woff2 .woff 中添加字体才能使其正常工作。

css 示例:

@font-face {
    font-family: 'yourFONT';
    src: url(/yourFont.eot');
    src: url('/yourFont.eot?#iefix') format('embedded-opentype'),
         url('/yourFont.woff2') format('woff2'),
         url('/yourFont.woff') format('woff'),
         url('/yourFont.ttf') format('truetype'),
         url('/yourFont.svg#yourFONT') format('svg');
    font-weight: normal;
    font-style: normal;
}