canvas实现文字水平垂直居中
eg:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>canvas实现文字水平垂直居中</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="300">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
const w = 200,
h = 200;
ctx.fillStyle = "#3458a4";
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = "rgba(255,255,255)";
ctx.font = "50px 微软雅黑";
ctx.textAlign = 'center'; // 设置水平对齐方式
ctx.textBaseline = "middle"; // 设置垂直对齐方式
ctx.fillText('test', w / 2, h /
2); // 需要将fillText的第二个参数,也就是文字在x轴的位置,设置为宽度的一半;需要将fillText的第三个参数,也就是文字在y轴的位置,设置为高度的一半。
</script>
</body>
</html>
效果图
结论:
1.设置textAlign属性为’center’
2.设置textBaseline属性为’middle’
3.调用fillText方法时,第二个参数【开始绘制文本的 x 坐标位置(相对于画布)】的值为文字所需居中的宽度的一半,第三个参数【开始绘制文本的 y 坐标位置(相对于画布)】是的值为文字所需居中的高度的一半