文本垂直对齐方式
1. 前言
我们前面讲的 canvas 只能绘制单行文本,单行文本怎么会有垂直对齐呢?其实,这里的垂直对齐是指文本基线与单行文本的对齐,类似 CSS 中的 vertical-align
概念,本小节我们就来学习一下文本的垂直对齐。
2. 垂直对齐
canvas 为我们提供了一个文字基线与文本的垂直关系设置的属性 textBaseline
,这里的基线设置和 CSS 的 vertical-align
概念很类似,也可以想象成我们学习拼音时使用的四线三格图。在电脑和手机上,每个汉字或者字符在设计的时候都有自己的排版方式。
例如这样:
我们把这六条线从上到下命名为:
top
hanging
middle
alphabetic
ideographic
bottom
明白了上面的,我们就来看 canvas 是怎么设置基线的。
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的浏览器不支持 HTML5 canvas 标签</canvas>
<script>
const canvas = document.getElementById('imooc');
canvas.width=;
canvas.height=;
const ctx = canvas.getContext('2d');
ctx.fillStyle="#456795";
ctx.font="20px 微软雅黑";
ctx.beginPath()
ctx.strokeStyle="#ccc";
ctx.moveto(,);
ctx.lineto(,);
ctx.stroke();
ctx.textBaseline="top" //设置基线在文本顶部,文本和基线重合
ctx.fillText("Wiki textBaseline = top", ,)
ctx.beginPath()
ctx.strokeStyle="#ccc";
ctx.moveto(,);
ctx.lineto(,);
ctx.stroke();
ctx.textBaseline="hanging" //设置文本悬挂在基线上,文本和基线没有重合
ctx.fillText("Wiki textBaseline = hanging", ,)
ctx.beginPath()
ctx.strokeStyle="#ccc";
ctx.moveto(,);
ctx.lineto(,);
ctx.stroke();
ctx.textBaseline="middle" //设置基线在文本中间
ctx.fillText("Wiki textBaseline = middle", ,)
ctx.beginPath()
ctx.strokeStyle="#ccc";
ctx.moveto(,);
ctx.lineto(,);
ctx.stroke();
ctx.textBaseline="alphabetic" //标准的字母基线
ctx.fillText("Wiki textBaseline = alphabetic", ,)
ctx.beginPath()
ctx.strokeStyle="#ccc";
ctx.moveto(,);
ctx.lineto(,);
ctx.stroke();
ctx.textBaseline="ideographic"
ctx.fillText("Wiki textBaseline = ideographic", ,)
ctx.beginPath()
ctx.strokeStyle="#ccc";
ctx.moveto(,);
ctx.lineto(,);
ctx.stroke();
ctx.textBaseline="bottom"
ctx.fillText("Wiki textBaseline = bottom", ,)
</script>
<body>
</html>
运行结果:
这样我们就绘制了一个文本的垂直对齐。
3. 属性整理
3.1 对齐设置 textBaseline
textBaseline 说明
语法:
ctx.textBaseline = value;
取值说明:
4. 总结
本小节我们主要学习了利用 textBaseline
设定文本垂直对齐方式。