Skip to content

Fix WebGL text alignment + add tests #7481

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/type/text2d.js
Original file line number Diff line number Diff line change
Expand Up @@ -518,12 +518,16 @@ function text2d(p5, fn) {

// adjust the bounding boxes based on horiz. text alignment
if (lines.length > 1) {
boxes.forEach(bb => bb.x += this._xAlignOffset(textAlign, width));
// Call the 2D mode version: the WebGL mode version does additional
// alignment adjustments to account for how WebGL renders text.
boxes.forEach(bb => bb.x += p5.Renderer2D.prototype._xAlignOffset.call(this, textAlign, width));
}

// adjust the bounding boxes based on vert. text alignment
if (typeof height !== 'undefined') {
this._yAlignOffset(boxes, height);
// Call the 2D mode version: the WebGL mode version does additional
// alignment adjustments to account for how WebGL renders text.
p5.Renderer2D.prototype._yAlignOffset.call(this, boxes, height);
}

// get the bounds for the text block
Expand Down Expand Up @@ -1224,11 +1228,11 @@ function text2d(p5, fn) {
case fn.LEFT:
adjustedX = x;
break;
case fn._CTX_MIDDLE:
adjustedX = x + (adjustedW - widths[i]) / 2;
case fn.CENTER:
adjustedX = x + (adjustedW - widths[i]) / 2 - adjustedW / 2 + (width || 0) / 2;
break;
case fn.RIGHT:
adjustedX = x + adjustedW - widths[i];
adjustedX = x + adjustedW - widths[i] - adjustedW + (width || 0);
break;
case fn.END:
throw new Error('textBounds: END not yet supported for textAlign');
Expand All @@ -1255,10 +1259,10 @@ function text2d(p5, fn) {
case fn.BASELINE:
break;
case fn._CTX_MIDDLE:
yOff = -totalHeight / 2 + textSize;
yOff = -totalHeight / 2 + textSize + (height || 0) / 2;
break;
case fn.BOTTOM:
yOff = -(totalHeight - textSize);
yOff = -(totalHeight - textSize) + (height || 0);
break;
default:
console.warn(`${textBaseline} is not supported in WebGL mode.`); // FES?
Expand Down
2 changes: 1 addition & 1 deletion src/webgl/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ function text(p5, fn){
console.log(
'WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts are supported'
);
return p;
return;
}

this.push(); // fix to #803
Expand Down
Loading
Loading