Search code examples
konvajskonva

How to get Konva.TextPath width considering additional parameters


Good day, reader.

I am trying to create curved text with dynamic path using Konva, so I am transferring Konva.Text to Konva.TextPath, adding to Text attrs calculated path (code sample is written in the end), although I can't get Konva.TextPath's right width taking into consideration additional parameters listed below. I tried this methods`

  • textNode.textwidth
  • textNode.width()
  • textNode.textWidth()
  • textNode.getClientRect().width // wrong size when curved

The most close to what I want is 3th option (it seems that it's same as 1st?).

Is there anyway to get width of Konva.TextPath considering also parameters like `

  • font,
  • font-size,
  • letter-spacing,

I read documentation, looked through stackoverflow, but couldn't find any way. Is there something I'm missing out ?

function redraw(originTextNode: Konva.Text | Konva.TextPath)
   const textWidth = textNode.textWidth();
   const calcedNewPath = calcNewPath({...other, textWidth })

   const textNode = Konva.TextPath({
     ...originTextNode.getAttrs(),
     data: calcedNewPath,
});

Thanks


Solution

  • You can use textPath.getTextWidth() to get width of the text without letterSpacing adjustments. It will include fontFamily (if font is loaded) and fontSize. If you want to apply letterSpacing to that value you can do this:

    var fullWidth = textPath.getTextWidth() + (textPath.text().length - 1) * letterSpacing;
    

    The actual length of the rendered text path can be still a bit different compared to the length of the path.