diff --git a/src/shapes/Text.ts b/src/shapes/Text.ts index 20eefa7e4..1ecdedb5e 100644 --- a/src/shapes/Text.ts +++ b/src/shapes/Text.ts @@ -201,11 +201,18 @@ export class Text extends Shape { shouldUnderline = textDecoration.indexOf('underline') !== -1, shouldLineThrough = textDecoration.indexOf('line-through') !== -1, n; - + direction = direction === INHERIT ? context.direction : direction; - var translateY = 0; var translateY = lineHeightPx / 2; + const baseline = this.textBaseline(); + if (baseline === 'alphabetic') { + var metrics = this.measureSize('M'); // Use a sample character to get the ascent + + translateY = + (metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2 + + lineHeightPx / 2; + } var lineTranslateX = 0; var lineTranslateY = 0; @@ -216,11 +223,10 @@ export class Text extends Shape { context.setAttr('font', this._getContextFont()); - context.setAttr('textBaseline', MIDDLE); + context.setAttr('textBaseline', baseline); context.setAttr('textAlign', LEFT); - // handle vertical alignment if (verticalAlign === MIDDLE) { alignY = (this.getHeight() - textArrLen * lineHeightPx - padding * 2) / 2; @@ -399,6 +405,18 @@ export class Text extends Shape { metrics = _context.measureText(text); _context.restore(); return { + // copy all text metrics data: + actualBoundingBoxAscent: metrics.actualBoundingBoxAscent, + actualBoundingBoxDescent: metrics.actualBoundingBoxDescent, + actualBoundingBoxLeft: metrics.actualBoundingBoxLeft, + actualBoundingBoxRight: metrics.actualBoundingBoxRight, + alphabeticBaseline: metrics.alphabeticBaseline, + emHeightAscent: metrics.emHeightAscent, + emHeightDescent: metrics.emHeightDescent, + fontBoundingBoxAscent: metrics.fontBoundingBoxAscent, + fontBoundingBoxDescent: metrics.fontBoundingBoxDescent, + hangingBaseline: metrics.hangingBaseline, + ideographicBaseline: metrics.ideographicBaseline, width: metrics.width, height: fontSize, }; @@ -637,6 +655,7 @@ export class Text extends Shape { direction: GetSet; fontFamily: GetSet; + textBaseline: GetSet; fontSize: GetSet; fontStyle: GetSet; fontVariant: GetSet; @@ -703,7 +722,6 @@ Factory.overWriteSetter(Text, 'width', getNumberOrAutoValidator()); Factory.overWriteSetter(Text, 'height', getNumberOrAutoValidator()); - /** * get/set direction * @name Konva.Text#direction @@ -734,6 +752,8 @@ Factory.addGetterSetter(Text, 'direction', INHERIT); */ Factory.addGetterSetter(Text, 'fontFamily', 'Arial'); +Factory.addGetterSetter(Text, 'textBaseline', MIDDLE); + /** * get/set font size in pixels * @name Konva.Text#fontSize diff --git a/test/sandbox.html b/test/sandbox.html index 674c2c187..db4dda12d 100644 --- a/test/sandbox.html +++ b/test/sandbox.html @@ -30,46 +30,77 @@