如何根据分配的字体大小垂直对齐 Canvas 中的文本?例如,我有一个高度为100px的矩形,变量textSize
。我的目标是始终将文本垂直居中在这个特定的矩形内。
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();
最佳答案
This答案可能有帮助
Canvas 的上下文有 measureText您可以使用的功能。
关于javascript - 根据字体大小在 Canvas 中垂直居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746308/