Size to fit font on a canvas
You can use context.measureText to get the pixel width of any given text in the current font.
Then if that width is too big, reduce the font size until it fits.
context.font="14px verdana";
var width = context.measureText("Hello...Do I fit on the canvas?").width
if(width>myDesiredWidth) // then reduce the font size and re-measure
Demo:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
fitTextOnCanvas("Hello, World!", "verdana", 125);
function fitTextOnCanvas(text, fontface, yPosition) {
// start with a large font size
var fontsize = 300;
// lower the font size until the text fits the canvas
do {
fontsize--;
context.font = fontsize + "px " + fontface;
} while (context.measureText(text).width > canvas.width)
// draw the text
context.fillText(text, 0, yPosition);
alert("A fontsize of " + fontsize + "px fits this text on the canvas");
}
body {
background-color: ivory;
}
#canvas {
border: 1px solid red;
}
<canvas id="canvas" width=300 height=300></canvas>
Simple and efficient solution for DOM environment, no loops, just do one sample measurement and scale the result appropriately.
function getFontSizeToFit(text: string, fontFace: string, maxWidth: number) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.font = `1px ${fontFace}`;
return maxWidth / ctx.measureText(text).width;
}
Beware that if you use npm 'canvas' module for NodeJs environment, the result won't be that accurate as they use some custom C++ implementation that returns only integer sample width.