绘制文本
- ctx.font = ‘微软雅黑’ 设置字体
- strokeText()
- fillText(text,x,y,maxWidth)
- text 要绘制的文本
- x,y 文本绘制的坐标(文本左下角)
- maxWidth 设置文本最大宽度,可选参数
- ctx.textAlign文本水平对齐方式,相对绘制坐标来说的
- left
- center
- right
- start 默认
- end
- ctx.direction属性css(rtl ltr) start和end于此相关
- 如果是ltr,start和left表现一致
- 如果是rtl,start和right表现一致
- ctx.textBaseline 设置基线(垂直对齐方式 )
- top 文本的基线处于文本的正上方,并且有一段距离
- middle 文本的基线处于文本的正中间
- bottom 文本的基线处于文本的证下方,并且有一段距离
- hanging 文本的基线处于文本的正上方,并且和文本粘合
- alphabetic 默认值,基线处于文本的下方,并且穿过文字
- ideographic 和bottom相似,但是不一样
- measureText() 获取文本宽度obj.width
//绘制一段文字
var ctx = document.querySelector("canvas").getContext("2d");
var w = ctx.canvas.width;
var h = ctx.canvas.height;
//文字
var txt = "好冷好冷";
//绘制水平垂直线
ctx.beginPath();
ctx.moveTo(0, h / 2 - 0.5);
ctx.lineTo(w, h / 2 - 0.5);
ctx.moveTo(w /2 , 0);
ctx.lineTo(w /2, h );
ctx.strokeStyle = "#eee";
ctx.stroke();
//绘制文本
ctx.beginPath();
ctx.font = "40px Microsoft YaHei";
//水平对齐方式
ctx.textAlign = "center";
//垂直对齐方式
ctx.textBaseline = "middle";
ctx.fillText(txt, w / 2, h / 2);
//画下划线和文字一样长
ctx.beginPath();
var width = ctx.measureText(txt).width;
ctx.moveTo(w / 2 - width / 2, h / 2 + 20);
ctx.lineTo(w / 2 + width / 2, h / 2 + 20);
ctx.strokeStyle = "#000";
ctx.stroke();
效果图