canvas标签textBaseline设置当前文本基线。
将每个单词放在y=100与不同的文本基线值
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>画布文本基线-HTML教程www.xuandaima.com</title> </head> <body> <canvas id="myCanvas" width="400" height="150" style="border:1px solid #d3d3d3;"> 您的浏览器不支持 HTML5 canvas 标签。 </canvas> <script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); //在Y轴位置100处创建一个蓝线 ctx.strokeStyle="blue"; ctx.moveTo(5,100); ctx.lineTo(395,100); ctx.stroke(); ctx.font="15px Arial"; // 将每个单词放在y=100与不同的文本基线值 ctx.textBaseline="top"; ctx.fillText("Top",5,100); ctx.textBaseline="hanging"; ctx.fillText("hanging",40,100); ctx.textBaseline="middle"; ctx.fillText("middle",110,100); ctx.textBaseline="alphabetic"; ctx.fillText("alphabetic",170,100); ctx.textBaseline="ideographic"; ctx.fillText("ideographic",250,100); ctx.textBaseline="bottom"; ctx.fillText("bottom",340,100); </script> </body> </html>
document.getElementById("myCanvas2") | 返回文档id属性为"myCanvas2"的对象 |
getContext("2d") | getContext() 返回画布上绘图的环境。getContext("2d") 返回绘制类型(2 维)的环境,未来可能会支持3维,但现在支持2维。 |
strokeStyle="blue" | 定义笔触颜色为蓝色。。 |
moveTo(5,100) | 定义开始点X坐标为5,Y坐标为100。 |
lineTo(395,100) | 定义第二个点X坐标为395,Y坐标为100。 |
stroke() | 使用笔触绘画。 |
font="15px Arial" | 定义一个字体为Arial大小为15像素。 |
textBaseline="top" | 定义文本基线属性为顶端位置。 |
fillText("Top",5,100) | 定义填充文本为"Top",位置在X坐标为50,Y坐标为100。 |
textBaseline="hanging" | 定义文本基线属性为悬挂位置。 |
fillText("hanging",40,100) | 定义填充文本为"hanging",位置在X坐标为40,Y坐标为100。 |
textBaseline="middle" | 定义文本基线属性为正中位置。 |
fillText("middle",110,100) | 定义填充文本为"middle",位置在X坐标为110,Y坐标为100。 |
textBaseline="alphabetic" | 定义文本基线属性为字母位置。 |
fillText("alphabetic",170,100) | 定义填充文本为"alphabetic",位置在X坐标为170,Y坐标为100。 |
textBaseline="ideographic" | 定义文本基线属性为表意位置。 |
fillText("ideographic",250,100) | 定义填充文本为"ideographic",位置在X坐标为250,Y坐标为100。 |
textBaseline="bottom" | 定义文本基线属性为底部位置。 |
fillText("bottom",340,100) | 定义填充文本为"bottom",位置在X坐标为340,Y坐标为100。 |
![]() | 该基线是基于fillText方法的Y的值,也就是100的位置。textBaseline需要配合strokeText()或fillText()方法使用。 |
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
context.textBaseline="alphabetic|top|hanging|middle|ideographic|bottom";
textBaseline 属性支持的各种基线
值 | 描述 |
---|---|
alphabetic | 默认。文本基线是普通的字母基线。 |
top | 文本基线是 em 方框的顶端。。 |
hanging | 文本基线是悬挂基线。 |
middle | 文本基线是 em 方框的正中。 |
ideographic | 文本基线是表意基线。 |
bottom | 文本基线是 em 方框的底端。 |