JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id='myCanvas'></canvas>
<div id='results'></div>
<div id='fontCanvas' style="display:none;"></div>
JavaScript
var scratchDiv = document.getElementById("fontCanvas");
var cssTextStyle = "width: 320px; font-size: 20pt; font-family: Georgia; line-height: 25px; color: rgb(227, 237, 241); text-shadow: rgb(57, 152, 179) 1px 1px;";
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "20pt Georgia";
var text = "Something happened, we're notifying you of it so you don't miss it and then get angry. That would be very bad indeed... And I suppose you'd blame *us* for that, wouldn't you? Typical.";
// Bespin hack, I guess. Doesn't actually work for getting font-size in px;
//var fontPxSize = ctx.measureText("M").width;
// ... or hardcode to match declaration above
var fontPxSize = 27;
console.log("Font size: ", fontPxSize);
var measureHeightNaive = function (ctx, fontPxSize, layoutWidth, text) {
var textWidth = ctx.measureText(text).width;
var textHeight = textWidth / layoutWidth * fontPxSize;
return textHeight;
}
var measureHeightWithWordWrap = function (ctx, fontPxSize, layoutWidth, text) {
var spaceWidth = ctx.measureText(" ").width;
var words = text.split(" ");
var lineCount = 1;
var offset = 0;
var wordWidth;
for (var i = 0; i < words.length; i++) {
wordWidth = ctx.measureText(words[i]).width;
offset = offset + wordWidth + spaceWidth;
if (offset > layoutWidth) {
//console.log("Line break!");
offset = wordWidth;
lineCount = lineCount + 1;
}
}
//console.log("Line count: ", lineCount);
return fontPxSize * lineCount;
}
var measureHeightWithDiv = function (divEl, cssTextStyle, layoutWidth, html) {
divEl.style.cssText = cssTextStyle;
divEl.style.display = "none;";
divEl.innerHTML = html;
return divEl.getClientRects()[0].height;
}
console.log(measureHeightNaive(ctx, fontPxSize, 320, text))
console.log(measureHeightWithWordWrap(ctx, fontPxSize, 320, text))
console.log(measureHeightWithDiv(scratchDiv, cssTextStyle,...