Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Draw centered text on a canvas, maximally filling a given maxWidth/maxHeight.
function centerText(text, canvas, config) {
var ctx = canvas.getContext('2d');
var x = config.x;
var y = config.y;
var maxWidth = config.maxWidth || canvas.width;
var maxHeight = config.maxHeight || canvas.height;
var lineHeight = config.lineHeight || 1.2;
var fontFamily = config.fontFamily || 'sans-serif';
ctx.save();
var lines = text.split('\n');
var fontSize = 10; // a reasonable starting point?
ctx.font = fontSize + 'px "' + fontFamily + '"';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var curWidth = 0;
lines.forEach(line =>
curWidth = Math.max(curWidth, ctx.measureText(line).width)
);
var curHeight = (lines.length - 1) * lineHeight * fontSize + fontSize;
var widthScale = maxWidth / curWidth;
var heightScale = maxHeight / curHeight;
var scale = Math.min(widthScale, heightScale);
fontSize *= scale;
ctx.font = fontSize + 'px "' + fontFamily + '"';
var finalWidth = curWidth * scale;
var finalHeight = curHeight * scale;
y -= (finalHeight - fontSize) / 2;
for (var i = 0; i < lines.length; i++) {
ctx.fillText(lines[i], x, y + i * fontSize * lineHeight)
}
ctx.restore();
return {
fontSize: fontSize,
x: x,
y: y,
width: finalWidth,
height: finalHeight
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment