绘制文字text
绘制语句
- 设置文本字号字体 context.font = “Npx 字体”;
默认为10px - 描边文字(空心) contenxt.strokeText(“文本”, x, y);
- 描边文字(实心) contenxt.fillText(“文本”, x, y);
设置文本对齐方式
- 文字的水平对齐context.textAlign=”left/ right/ center”;
-默认样式为left
-除此以外还有start、end - 文字的垂直对齐 context.textBaseline =”top/ bottom/ middle”
-默认为基线对齐alphabetic
-除此以外还有hanging、ideographic
文本宽度计算方法 var result= measureText(“文本”);
result为一个对象,计算出的宽度值=result.width;
设置文本方向 context.direction = “inherit/ ltr/ rtl”
-默认样式为inherit
案例:九宫格文字
最终呈现:
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.moveTo(0,200); //四根宫格线
context.lineTo(600,200);
context.moveTo(0,400);
context.lineTo(600,400);
context.moveTo(200,0);
context.lineTo(200,600);
context.moveTo(400,0);
context.lineTo(400,600);
context.stroke();
context.font="20px 微软雅黑";
//左上
context.textAlign = "left";
context.textBaseline = "top";
context.fillText("leftTop",0,0);
//左下
context.textBaseline = "bottom";
context.fillText("leftBottom",0,600);
//左中
context.textBaseline = "middle";
context.fillText("leftMiddle",0,300);
//右上
context.textAlign = "right";
context.textBaseline = "top";
context.fillText("rightTop",600,0);
//右下
context.textBaseline = "bottom";
context.fillText("rightBottom",600,600);
//右中
context.textBaseline = "middle";
context.fillText("rightmiddle",600,300);
//中上
context.textAlign = "center";
context.textBaseline = "top";
context.fillText("centerTop",300,0);
//中下
context.textBaseline = "bottom";
context.fillText("centerBottom",300,600);
//中中
context.textBaseline = "middle";
context.fillText("centerMiddle",300,300);
</script>