HTML canvas textBaseline 属性

由网友 大卫 发布 阅读 7

HTML canvas textBaseline 属性

textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。

HTML canvas 参考手册

在线示例

在y = 100处画一条红线,然后将每个单词在y = 100处放置不同的textBaseline值:

您的浏览器,不支持HTML5 canvas标签.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML canvas textBaseline属性使用-大卫编程网(div.cn)</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
//在Y = 100画一条红线
ctx.strokeStyle="red";
ctx.moveTo(5,100);
ctx.lineTo(395,100);
ctx.stroke();
ctx.font="20px Arial"
//每个在y = 100的单词有不同的textbaseline值
ctx.textBaseline="top"; 
ctx.fillText("Top",5,100); 
ctx.textBaseline="bottom"; 
ctx.fillText("Bottom",50,100); 
ctx.textBaseline="middle"; 
ctx.fillText("Middle",120,100); 
ctx.textBaseline="alphabetic"; 
ctx.fillText("Alphabetic",190,100); 
ctx.textBaseline="hanging"; 
ctx.fillText("Hanging",290,100); 
</script>
</body>
</html>
测试看看 ‹/›

浏览器兼容性

IEFirefoxOperaChromeSafari

Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 textBaseline 属性。

注意:textBaseline 属性在不同的浏览器上效果不同,特别是使用 "hanging" 或 "ideographic" 时。

注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。

定义和用法

textBaseline属性设置或返回在绘制文本时使用的当前文本基线。

下面的图示演示了 textBaseline 属性支持的各种基线:

textBaseline illustration

注意:fillText()strokeText() 方法在画布上定位文本时,将使用指定的 textBaseline 值。

默认值:alphabetic
JavaScript 语法:context.textBaseline="alphabetic|top|hanging|middle|ideographic|bottom";

属性值

描述
alphabetic默认。文本基线是普通的字母基线。
top文本基线是 em 方框的顶端。
hanging文本基线是悬挂基线。
middle文本基线是 em 方框的正中。
ideographic文本基线是表意基线。
bottom文本基线是 em 方框的底端。
HTML canvas 参考手册

HTML canvas fillText() 方法 HTML canvas textAlign 属性