【发布时间】:2021-04-28 03:26:10
【问题描述】:
我正在使用sharp image library 向图像添加文本标签。使用 sharp 向图像添加文本的唯一方法是创建一个 svg 并使用复合函数将其应用到源图像上。
let width = 100;
let height = 25;
let label = "Loooooooooong Text"; // "Medium Text" "Short"
const label = Buffer.from(`
<svg width="${width}" height="${height}">
<rect x="0" y="0" width="100%" height="100%" fill="#fff" />
<text x="50%" y="50%" text-anchor="middle" dy="0.25em" fill="#000">${label}</text>
</svg>
`);
let image = await sharp({
create: {
width: width,
height: height,
channels: 4,
background: { r: 255, g: 255, b: 255, alpha: 1 },
}
}).composite([{
input: label,
top: 0,
left: 0,
}]).png().toBuffer();
但是,我无法让文本正确使用容器中的可用空间。文本应在 svg 中垂直和水平居中。文本应尽可能高,但不会水平溢出容器。
这是我的代码使用不同的 label 值生成的结果:
这是我希望它产生的理想效果:
此外,由于issue in sharp,我不能使用dominant-baseline="middle" 将我的文本垂直居中,而是必须使用dy="0.25em"。我不确定这是否会改变答案,但我认为值得一提。
【问题讨论】: