绘制文本的方式
- 填充文字
ctx.fillText(内容, x, y, maxLength);
- 描边文字
ctx.strokeText(内容, x, y, maxLength)
参数说明:x,y: 坐标, maxLength: 文本最大宽度
1. font属性
设置font
ctx.font = '20px bold Arial';
字体大小
font-size
字体样式
font-style: normal; 默认正常
italic 斜体字
oblique 倾斜字体
字体加粗
font-weight: normal
lighter
bold
border
font-family: 可设置多个字体 支持@font-face web安全字体
看一下设置的效果:
ctx.font = 'italic bold 50px Arial';
ctx.fillText('italic', 50, 50);
ctx.font = 'oblique bold 50px Arial';
ctx.fillText('oblique', 50, 150);
ctx.font = ' bold 50px Arial';
ctx.fillText('Hello,小贝同学', 50, 250);
ctx.font = 'small-caps bold 50px sans-serif';
ctx.fillText('Hello,小贝同学', 50, 350);
![](https://img.haomeiwen.com/i15804534/b24098fac067c34f.gif)
文本的水平对齐方式
ctx.textAlign = '位置'
文本在指定的位置开始(默认 )
ctx.textAlign = 'start'; // 同left
ctx.strokeText('start', 150, 50);
文本的中心被放置在指定的位置
ctx.textAlign = 'center';
ctx.strokeText('center', 150, 100);
文本在指定的位置结束
ctx.textAlign = 'end'; // right
ctx.strokeText('end', 150, 150);
垂直对齐方式
ctx.textBaseline = '位置'
文本基线是普通的字母基线(默认[图片上传中...(绘制文字.PNG-4c501b-1559625787811-0)]
)
文本基线是em方框的底端
// 修改填充颜色
ctx.fillStyle = 'red';
ctx.textAlign = 'start';
ctx.textBaseline = 'alphabetic';
ctx.fillText('alphabetic', 240, 250);
文本基线是em方框的顶端
ctx.textBaseline = 'top';
ctx.fillText('top', 5, 250);
文本基线是悬挂基线
ctx.textBaseline = 'hanging';
ctx.fillText('hanging', 50, 250);
文本基线是em方框的正中
ctx.textBaseline = 'middle';
ctx.fillText('middle', 150, 250);
文本基线是em方框的底端
ctx.textBaseline = 'ideographic';
ctx.fillText('ideographic', 370, 250);
文本的度量
返回一个对象,存储的是字符串的度量对象, (当前字符串长度为多少)
ctx.measureText(string)
ctx.font = '20px bold';
console.log(ctx.measureText('小贝老师').width); // 80
网友评论