要将文本与HTML5 Canvas垂直对齐,我们可以使用画布上下文的textBaseline属性。 textBaseline可以使用以下值之一进行设置:top,hanging,middle,alphabetic,ideographic和bottom。 除非另行指定,否则textBaseline属性默认为字母。
html代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
context.font = '30pt Calibri';
// textAlign aligns text horizontally relative to placement
context.textAlign = 'center';
// textBaseline aligns text vertically relative to font style
context.textBaseline = 'middle';
context.fillStyle = 'blue';
context.fillText('Hello World!', x, y);
</script>
</body>
</html>