HTML5 Canvas,导入本地字体?

时间:2018-04-16 17:03:10

标签: javascript css html5 fonts html5-canvas

我正在尝试导入要在html5画布中使用的字体。我的计算机上有这个文件,但到目前为止我尝试的所有内容都没有用。画布只显示默认字体。我必须做错事或错过一步。

我已经用这样的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更改为另一个值时,字体的大小都会发生变化。我想我必须正确加载实际的字体文件。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

自定义字体 - 字体字体在使用之前不会加载(您可以阅读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);
    }
    

    只需在需要使用字体之前调用该函数,并在实际需要时加载它们。

答案 1 :(得分:0)

示例中的实际问题似乎是url和format参数之间的逗号(,)。 format应该直接关注网址:

src: local('RifficFree-Bold'), url(./fonts/RifficFree-Bold.ttf) format('truetype');