Created
April 16, 2019 23:46
-
-
Save kylemcdonald/ef3fe55aba4296602a1d5d23f496bbba to your computer and use it in GitHub Desktop.
Draw centered text on a canvas, maximally filling a given maxWidth/maxHeight.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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