gpt4 book ai didi

node.js - 如何在 nodejs-canvas 上安装 Google 字体?

转载 作者:行者123 更新时间:2023-12-04 15:38:52 26 4
gpt4 key购买 nike

我正在尝试使用 nodejs-canvas 动态获取 Google 字体,但我不确定这样做的最佳方法是什么。
我知道它需要使用:“registerFont”方法。
这是我现在的代码:

const { registerFont, createCanvas, loadImage } = require('canvas')
//registerFont('comicsans.ttf', { family: 'Comic Sans' })
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d')

let name = req.query.name;

// Write "Awesome!"
ctx.font = '30px Impact'
ctx.rotate(0.1)
ctx.fillText(name, 50, 100)

// Draw line under text
var text = ctx.measureText(name)
ctx.strokeStyle = 'rgba(0,0,0,0.5)'
ctx.beginPath()
ctx.lineTo(50, 102)
ctx.lineTo(50 + text.width, 102)
ctx.stroke()

//console.log(canvas.toDataURL());

res.write('<img style="border:1px solid #000;" src="' + canvas.toDataURL() + '" />');
res.end();

最佳答案

以 PT Mono 为例,这就是您的做法。

  • 这种情况先直接去字体PT Mono .
  • 接下来单击右上角的“下载系列”链接。这将为您提供一个包含 TTF 字体的 zip 文件。
  • 现在将 ttf 文件复制到您的 Node 应用程序目录并使用 registerFont在这样的文件中。
  • registerFont('PtMono-Regular.ttf', { family: 'PT Mono' });
    根据文档,请确保在创建 Canvas 之前注册您的字体。

    然后要在 Canvas 上使用您的字体,您只需使用以下内容来设置上下文的字体。
    ctx.font = "16px 'PT Mono'";
    使用我们的 google 字体的完整示例只是修改了 node-canvs repo 中的原始示例.
    const { registerFont, createCanvas } = require('canvas');
    registerFont('PtMono-Regular.ttf', { family: 'PT Mono' });

    const canvas = createCanvas(500, 500);
    const ctx = canvas.getContext('2d');

    ctx.font = '16px 'PT Mono'"'
    ctx.fillText('This is the font.', 250, 10);

    关于node.js - 如何在 nodejs-canvas 上安装 Google 字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58753333/

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