canvas--绘制文本

绘制文本(Drawing Text)

1.1 fillText(text,x,y,[,maxWidth]) 在指定的(x,y)位置填充指定的文本,绘制的最大宽度是可选的.

1
2
3
4
5
6
7
8
function draw() {
var canvas = document.getElementById('tutorial');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.font = "18px serif";
ctx.fillText("Hello World", 10, 50)
}
}

效果如下:

1.2 strokeText(text,x,y,[,maxWidth]) 在指定的(x,y)位置绘制文本边框,绘制的最大宽度是可选的.

1
2
3
4
5
6
7
8
function draw() {
var canvas = document.getElementById('tutorial');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.font = "18px serif";
ctx.strokeText("Hello World", 10, 50)
}
}

效果如下:

2.有样式的文本(Styling Text)

2.1 设置字体 font = value 默认”10px sans-serif”

和 CSS font 属性相同的语法

2.1 设置文本对齐方式 textAlign = value 默认 “start”

可选值:start、end、left、right、center

2.1 设置基线对齐方式 textBaseline = value 默认 “alphabetic”

可选值:top、hanging、middle、alphabetic、ideographic、bottom

2.1 设置文本方向 direction = value 默认 “inherit”

可选值:ltr(left to right)、rtl(right to left)、inherit

1
2
3
4
5
6
7
8
9
10
11
function draw() {
var canvas = document.getElementById('tutorial');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.font = "18px serif";
ctx.textAlign = "start";
ctx.textBaseline = "hanging";
ctx.direction="ltr";
ctx.fillText("Hello World", 10, 50);
}
}

效果如下: