How do you vertically align text in canvas, based on the font size assigned? For instance, I have a rectangle with the height of 100px, and the variable textSize
. My goal is to always vertically center the text inside of this specific rectangle.
HTML
<canvas id="canvas" width="500" height="100"></canvas>
JS
var textSize = 40;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineTo(0, 100);
ctx.lineTo(0, 0);
ctx.lineTo(500, 0);
ctx.lineTo(500, 100);
ctx.closePath();
ctx.fillStyle = "#000";
ctx.fill();
ctx.closePath();
// Text
ctx.save();
ctx.font = textSize + "px 'Oswald'";
ctx.fillStyle = "#fff";
ctx.textBaseline="middle";
ctx.fillText("Hello, World", 100, (100 - textSize)/2);
ctx.restore();
}
window.onload = init();