Improve calculations for Text width to better align with CSS letter-spacing properties #1865
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request includes a change to the
Text
class in thesrc/shapes/Text.ts
file to adjust the width calculation by incorporating letter spacing.src/shapes/Text.ts
: Updated the width calculation in theText
class to includeletterSpacing
in theobj.width
value.Issue Description
While testing text alignment, I noticed a discrepancy between how Konva.Text and CSS handle letter spacing for center-aligned text. Specifically, CSS includes the letter-spacing after the last character when calculating the x-axis offset for center alignment, whereas Konva does not. This inconsistency results in text being slightly misaligned when using center alignment with letter spacing.
Proposed Fix
This pull request modifies Konva.Text to align its letter-spacing calculations with CSS behavior. The updated logic ensures that the x-axis offset for center-aligned text incorporates the letter-spacing value applied after the last character, matching CSS behavior precisely.
Screenshots
The yellow text in the screenshots is an HTML element styled to match the Konva text (black) exactly, with the same properties, text content, and letter-spacing applied. This provides a direct comparison between how the Konva text and a standard HTML element are rendered. The behavior shown is consistent across both screenshots.
In these examples letterSpacing is equal to 50% of the fontSize.
Original Konva Behavior vs. CSS: Highlights the misalignment issue.
Updated Konva Behavior (Post Fix): Demonstrates alignment consistency with CSS.
Notes
This is my first contribution to open source, and I welcome any feedback on improvements or omissions in this pull request. Thank you for taking the time to review this!