phaserjs / phaser-ce

Phaser CE is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
http://phaser.io
MIT License
1.36k stars 491 forks source link

Text rendering with word wrap and RTL often clips #664

Open oisact opened 4 years ago

oisact commented 4 years ago

When the word wrapping routine splits text into words by spaces, each line's string (except possibly the last line) has a trailing space. Each line is then measured, and the width of a space is removed from the line length to account for that trailing space (necessary for accurate Center or Right alignment). For LTR languages, the trailing space for the widest line(s) are actually clipped off by the right side of the context's rectangle because of this. Since spaces are not visible, this is not an issue.

For a RTL language the trailing space is actually drawn on the left. Since text rendering is positioned by the left edge, the subtraction of the width of a space from the width of the line may result in the right side of the text clipped by the width of the space.

Fix: Instead of measuring lines of word wrapped split text with trailing space included, then subtracting the width of a space, simply trim the trailing space of each word wrapped line from the string.

oisact commented 4 years ago

This corrects the defect.

Addition of 5 lines to Text.js:

    this._charCount = 0;

    for (var i = 0; i < drawnLines; i++)
    {
        if (this.style.wordWrap && lines[i].length > 0 && lines[i][lines[i].length-1] == ' ')
        {
            //Remove trailing space from word wrapped lines.
            lines[i] = lines[i].substring(0, lines[i].length-1);
        }
        if (tabs === 0)
        {

Remove from Text.js

`            // Adjust for wrapped text
            if (this.style.wordWrap)
            {
                lineWidth -= this.context.measureText(' ').width;
            }
oisact commented 4 years ago

Additionally, it is possible for this defect to manifest for LTR languages as well. The final word-wrapped line will not end in a space (unless the original text has an extraneous space at the end) when words are split by spaces. The defective code assumes every line, including the final line, ends in a space. Thus if the final word wrapped line is the widest line, it could also be clipped by the width of a space.

samme commented 4 years ago

Thanks. So what's a text string I could reproduce this with?

oisact commented 4 years ago

I'm checking with the copyright owners over that. I think if I provide you the raw text, font size and the word wrap width constraint you should be able to reproduce it.