gpt4 book ai didi

javascript - HTML5 Canvas,导入本地字体?

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:16 26 4
gpt4 key购买 nike

我正在尝试导入一种字体以在 html5 Canvas 中使用。我的电脑上有文件,但到目前为止我尝试过的一切都没有奏效。 Canvas 仅显示默认字体。我一定是做错了什么或错过了一步。

我已经像这样用 CSS 加载了它们:

@font-face {
font-family: 'RifficFree-Bold';
src: local('RifficFree-Bold'), url(./fonts/RifficFree-Bold.ttf), format('truetype');
}

然后像这样在 JS 中调用它们:

    function drawText(myText, ctx) {
ctx.font = "40px RifficFree-Bold";
ctx.fillStyle = "rgb(0, 0, 0, " + myText.fill + ")";
ctx.fillText(myText.text, myText.x, myText.y);
}

我知道程序已经走到这一步了,因为每当我将 40px 更改为另一个值时,字体大小都会发生应有的变化。我想我一定是错误地加载了实际的字体文件。有什么想法吗?

最佳答案

自定义 font-face 字体在使用之前不会加载(您可以阅读 question about this here )。因此,当调用 drawText 函数时,字体不会开始加载,直到 ctx.fillText 被调用 - 此时文本已经使用默认字体绘制。

您可以通过两种方式强制浏览器预加载字体;

  1. 在页面某处放置一个小的、不可见的 div,其中包含一些使用您的字体的文本(可以在加载字体后将其删除)。

  2. 如果您需要加载多种字体或不想修改您的 HTML,您可以创建一个用于加载字体的小函数:

    function _loadFont(fontname){
    var canvas = document.createElement("canvas");
    //Setting the height and width is not really required
    canvas.width = 16;
    canvas.height = 16;
    var ctx = canvas.getContext("2d");

    //There is no need to attach the canvas anywhere,
    //calling fillText is enough to make the browser load the active font

    //If you have more than one custom font, you can just draw all of them here
    ctx.font = "4px "+fontname;
    ctx.fillText("text", 0, 8);
    }

    只需要在需要使用字体之前调用函数,真正需要的时候再加载。

关于javascript - HTML5 Canvas,导入本地字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49862696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com