title: [Node.js, sharp]: Make text take up 100% of SVG width
body: <p>I am using the <a href="https://sharp.pixelplumbing.com/" rel="nofollow noreferrer">sharp image library</a> 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.</p>
  <pre><code>let width = 100;
  let height = 25;
  let label = &quot;Loooooooooong Text&quot;; // &quot;Medium Text&quot; &quot;Short&quot;
  
  const label = Buffer.from(`
      &lt;svg width=&quot;${width}&quot; height=&quot;${height}&quot;&gt;
          &lt;rect x=&quot;0&quot; y=&quot;0&quot; width=&quot;100%&quot; height=&quot;100%&quot; fill=&quot;#fff&quot; /&gt;
          &lt;text x=&quot;50%&quot; y=&quot;50%&quot; text-anchor=&quot;middle&quot; dy=&quot;0.25em&quot; fill=&quot;#000&quot;&gt;${label}&lt;/text&gt;
      &lt;/svg&gt;
  `);
  
  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();
  </code></pre>
  <p>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.</p>
  <p>This is what my code produces with different values for <code>label</code>:</p>
  <p><a href="https://i.stack.imgur.com/MNwtk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MNwtk.png" alt="enter image description here" /></a></p>
  <p>This is ideally what I would like it to produce:</p>
  <p><a href="https://i.stack.imgur.com/UW7dC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UW7dC.png" alt="enter image description here" /></a></p>
  <p>Additionally, because of an <a href="https://github.com/lovell/sharp/issues/1996" rel="nofollow noreferrer">issue in sharp</a> I cannot use <code>dominant-baseline=&quot;middle&quot;</code> to center my text vertically and instead must use <code>dy=&quot;0.25em&quot;</code>. I'm not sure if this would change the answer but I thought it noteworthy to include.</p>