Scale multiple texts to width of canvas
A method to scale multiple texts to width of canvas
HTML
<canvas id="canvas" width=600 height=600></canvas>
CSS
body {
background-color: ivory;
}
#canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
texts = [
Math.random(),
" Whether you're a brother or whether you're a mother,",
"You're stayin' alive, stayin' alive.",
"Feel the city breakin' and everybody shakin',",
"And we're stayin' alive, stayin' alive.",
"Ah, ha,",
"ha, ha,",
"stayin' alive, stayin' alive.",
"------------------------------------"
]
yPos = 0;
texts.forEach(function(txt) {
var fontsize = fitTextOnCanvas(txt, "verdana");
yPos += fontsize;
// draw the text
context.fillText(txt, 0, yPos);
})
function fitTextOnCanvas(text, fontface) {
// start with a large font size
var fontsize = 1024;
// lower the font size until the text fits the canvas
do {
fontsize--;
context.font = fontsize + "px " + fontface;
} while (context.measureText(text).width > canvas.width)
return fontsize;
}