Skip to content

Commit adc1064

Browse files
committed
Better visual centering of text
1 parent 514df2a commit adc1064

File tree

67 files changed

+13
-2
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+13
-2
lines changed

src/type/textCore.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2518,6 +2518,17 @@ function textCore(p5, fn) {
25182518
return this._pInst;
25192519
};
25202520

2521+
Renderer.prototype._middleAlignOffset = function() {
2522+
const ctx = this.textDrawingContext();
2523+
const metrics = ctx.measureText('X');
2524+
return (
2525+
(metrics.fontBoundingBoxDescent +
2526+
(metrics.alphabeticBaseline || -metrics.fontBoundingBoxAscent / 2)) /
2527+
2 -
2528+
(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2
2529+
);
2530+
};
2531+
25212532
if (p5.Renderer2D) {
25222533
p5.Renderer2D.prototype.textCanvas = function () {
25232534
return this.canvas;
@@ -2607,7 +2618,7 @@ function textCore(p5, fn) {
26072618
case fn.BASELINE:
26082619
break;
26092620
case textCoreConstants._CTX_MIDDLE:
2610-
yOff = ydiff / 2;
2621+
yOff = ydiff / 2 + this._middleAlignOffset();
26112622
break;
26122623
case fn.BOTTOM:
26132624
yOff = ydiff;
@@ -2712,7 +2723,7 @@ function textCore(p5, fn) {
27122723
case fn.BASELINE:
27132724
break;
27142725
case textCoreConstants._CTX_MIDDLE:
2715-
yOff = (-totalHeight + textSize + (height || 0)) / 2 + this._verticalAlignFont();
2726+
yOff = (-totalHeight + textSize + (height || 0)) / 2 + this._verticalAlignFont() + this._middleAlignOffset();
27162727
break;
27172728
case fn.BOTTOM:
27182729
yOff = -(totalHeight - textSize) + (height || 0);
11 Bytes
20 Bytes
16 Bytes
302 Bytes
253 Bytes
240 Bytes
326 Bytes
271 Bytes
255 Bytes

0 commit comments

Comments
 (0)