JSFiddle - React, Tailwind, and code Playground
by Exceeder
HTML
<canvas width="500" height="100"></canvas>
<div style="clear:both"></div>
<div id="metrics">
<img id="ximg" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" width="42" height="10"></img>
ABCD
</div>
<div id="msg"</div>
CSS
#metrics {
display:inline;
font-size:36pt;
/*vertical-align:text-top; */
margin:0;
background:#eee;
width:200px;
border:none;
/*line-height:0;*/
}
#metrics > div { display:inlne; }
#metrics img {
display:inline;
background:black;
vertical-align:top;
}
JavaScript
var getTextHeight = function(font) {
var text = $('<span>Ag</span>');
text[0].style.font = font;
var block = $('<div style="display: inline-block; width: 1px; height: 0px;"></div>');
var div = $('<div></div>');
div.append(text, block);
var body = $('body');
body.append(div);
try {
var result = {};
block.css({ verticalAlign: 'baseline' });
result.ascent = block.offset().top - text.offset().top;
block.css({ verticalAlign: 'bottom' });
result.height = block.offset().top - text.offset().top;
block.css({ verticalAlign: 'text-top' });
result.unknown1 = result.ascent - (block.offset().top - text.offset().top);
result.descent = result.height - result.ascent;
} finally {
div.remove();
}
result.topBaseLine =
$('#ximg').offset().top -
$('#metrics').offset().top + 1;
$('#msg').html('aaa='+result.topBaseLine);
return result;
};
var testLine = function(ctx, x, y, len, style) {
ctx.strokeStyle = style;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + len, y);
ctx.closePath();
ctx.stroke();
};
var canvas = $('canvas');
canvas.click(function() {
window.open(canvas[0].toDataURL(), '');
});
var ctx = canvas[0].getContext('2d');
var x = 10;
var y = 10;
var font = '36pt Times';
var message = 'ABCD';
ctx.fillStyle = 'black';
ctx.textAlign = 'left';
ctx.textBaseline = 'top'; // important!
ctx.font = font;
ctx.fillText(message, x, y);
// Canvas can tell us the width
var w = ctx.measureText(message).width;
// New function gets the other info we need
var h = getTextHeight(font);
testLine(ctx, x, y, w, 'red');
testLine(ctx, x, y + h.ascent, w, 'green');
testLine(ctx, x, y + h.height, w, 'blue');
testLine(ctx, x, y + h.topBaseLine, w, 'black');