【发布时间】:2020-11-08 22:23:24
【问题描述】:
我正在尝试在 npm 模块 canvas 顶部使用 canvas-multiline-text 在画布上垂直居中对齐多行文本。我不知道如何(以编程方式/自动)垂直居中文本。
文本可能是 1 个单词,也可能是一个包含 10 个以上单词的句子。有没有办法计算出它的高度并相应地计算y 的位置?
注意:我不在浏览器中,我使用的是 node.js。
const fs = require('fs')
const { registerFont, createCanvas, loadImage } = require('canvas')
const drawMultilineText = require('canvas-multiline-text')
const width = 2000;
const height = 2000;
let fontSize = 250;
const canvas = createCanvas(width, height)
const context = canvas.getContext('2d')
//Filling the square
context.fillStyle = '#fff'
context.fillRect(0, 0, width, height)
//Text Styles
context.font = "normal 700 250px Arial";
context.textAlign = 'center'
context.textBaseline = 'middle';
context.fillStyle = '#000'
//Drawing Multi Line Text
const fontSizeUsed = drawMultilineText(
context,
"Hello World, this is a test",
{
rect: {
x: 1000,
y: 1000, // <-- not sure what to put here / how to calculate this?
width: context.canvas.width - 20,
height: context.canvas.height - 20
},
font: 'Arial',
verbose: true,
lineHeight: 1.4,
minFontSize: 100,
maxFontSize: 250
}
)
【问题讨论】:
标签: javascript css node.js canvas html5-canvas