我正在尝试使用 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();
Run Code Online (Sandbox Code Playgroud)
以 PT Mono 为例,您可以这样做。
首先直接转到字体,在本例中为PT Mono。
接下来单击右上角的“下载系列”链接。这将为您提供一个包含 TTF 字体的 zip 文件。
现在将 ttf 文件复制到节点应用程序目录中,并registerFont像这样在文件中使用。
registerFont('PtMono-Regular.ttf', { family: 'PT Mono' });
根据文档,请确保在创建画布之前注册字体。
然后,要在画布上使用您的字体,您只需使用以下内容来设置上下文的字体。
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2801 次 |
| 最近记录: |