2021年1月25日星期一

[Node.js, sharp]: Make text take up 100% of SVG width

I am using the sharp image library to add text labels to an image. The only way to add text to an image using sharp is by creating an svg and using the composite function to apply it onto the source image.

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();  

However, I am having trouble getting the text use the space available in the container properly. Text should be centered vertically and horizontally within the svg. Text should be as tall as it is possible without overflowing the container horizontally.

This is what my code produces with different values for label:

enter image description here

This is ideally what I would like it to produce:

enter image description here

Additionally, because of an issue in sharp I cannot use dominant-baseline="middle" to center my text vertically and instead must use dy="0.25em". I'm not sure if this would change the answer but I thought it noteworthy to include.

https://stackoverflow.com/questions/65865875/node-js-sharp-make-text-take-up-100-of-svg-width January 24, 2021 at 08:05AM

没有评论:

发表评论