Skip to content

Commit ca016c3

Browse files
authored
Merge pull request #8067 from Nitin2332/fix/textwidth-spaces
textWidth ignores leading and trailing spaces
2 parents f998af3 + 3efe5cb commit ca016c3

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/type/textCore.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,9 @@ function textCore(p5, fn) {
755755
*
756756
* For example, if the text contains multiple lines due to wrapping or explicit line breaks, textWidth()
757757
* will return the width of the longest line.
758+
*
759+
* **Note:** In p5.js 2.0+, leading and trailing spaces are ignored.
760+
* `textWidth(" Hello ")` returns the same width as `textWidth("Hello")`.
758761
*
759762
* @method textWidth
760763
* @for p5
@@ -821,6 +824,48 @@ function textCore(p5, fn) {
821824
* <div>
822825
* <code>
823826
* function setup() {
827+
* createCanvas(200, 160);
828+
* background(235);
829+
* noLoop();
830+
*
831+
* textSize(18);
832+
* textAlign(LEFT, TOP);
833+
*
834+
* const x = 12, h = 24;
835+
* const s1 = 'Hello';
836+
* const s2 = 'Hello '; // 2 trailing spaces
837+
* const s3 = 'Hello '; // many trailing spaces
838+
*
839+
* // draw text
840+
* fill(0);
841+
* text(s1, x, 12);
842+
* text(s2, x, 56);
843+
* text(s3, x, 100);
844+
*
845+
* // measure and draw tight boxes (all same width)
846+
* noFill(); stroke(255, 0, 0);
847+
* const w1 = textWidth(s1);
848+
* const w2 = textWidth(s2);
849+
* const w3 = textWidth(s3);
850+
* rect(x, 10, w1, h);
851+
* rect(x, 54, w2, h);
852+
* rect(x, 98, w3, h);
853+
*
854+
* // small captions show the actual strings (spaces as ·)
855+
* textSize(10); noStroke(); fill(30);
856+
* text('"' + s1.replace(/ /g, '·') + '" w=' + w1.toFixed(1), x, 10 + h + 2);
857+
* text('"' + s2.replace(/ /g, '·') + '" w=' + w2.toFixed(1), x, 54 + h + 2);
858+
* text('"' + s3.replace(/ /g, '·') + '" w=' + w3.toFixed(1), x, 98 + h + 2);
859+
*
860+
* describe('Three lines: Hello with 0, 2, and many trailing spaces. Red boxes use textWidth and are identical. Captions show spaces as dots.');
861+
* }
862+
* </code>
863+
* </div>
864+
*
865+
* @example
866+
* <div>
867+
* <code>
868+
* function setup() {
824869
* createCanvas(100, 100);
825870
*
826871
* background(200);

test/unit/type/attributes.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ suite('Typography Attributes', function() {
5050
test('should return a number for number input', function() {
5151
assert.isNumber(myp5.textWidth(100));
5252
});
53+
test('should ignore leading and trailing spaces', function() {
54+
assert.strictEqual(myp5.textWidth(' Hello '), myp5.textWidth('Hello'));
55+
assert.strictEqual(myp5.textWidth(' Hello '), myp5.textWidth('Hello'));
56+
});
5357
});
5458

5559
suite('textAscent', function() {

0 commit comments

Comments
 (0)