--- title: 绘制文本 slug: Web/API/Canvas_API/Tutorial/Drawing_text translation_of: Web/API/Canvas_API/Tutorial/Drawing_text ---
在前一个章节中看过 应用样式和颜色 之后, 我们现在来看一下如何在canvas中绘制文本
canvas 提供了两种方法来渲染文本:
文本用当前的填充方式被填充:
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = "48px serif";
ctx.fillText("Hello world", 10, 50);
}
<canvas id="canvas" width="300" height="100"></canvas>
draw();
{{EmbedLiveSample("A_fillText_example", 310, 110)}}
文本用当前的边框样式被绘制:
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = "48px serif";
ctx.strokeText("Hello world", 10, 50);
}
<canvas id="canvas" width="300" height="100"></canvas>
draw();
{{EmbedLiveSample("A_strokeText_example", 310, 110)}}
在上面的例子用我们已经使用了 font 来使文本比默认尺寸大一些. 还有更多的属性可以让你改变canvas显示文本的方式:
10px sans-serif。start, end, left, right or center. 默认值是 start。top, hanging, middle, alphabetic, ideographic, bottom。默认值是 alphabetic。ltr, rtl, inherit。默认值是 inherit。如果你之前使用过CSS,那么这些选项你会很熟悉。
下面的图片(from the WHATWG)展示了textBaseline属性支持的不同的基线情况:

编辑下面的代码,看看它们在canvas中的变化:
ctx.font = "48px serif";
ctx.textBaseline = "hanging";
ctx.strokeText("Hello world", 0, 100);
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
<input id="edit" type="button" value="Edit" />
<input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.font = "48px serif";
ctx.textBaseline = "hanging";
ctx.strokeText("Hello world", 0, 100);</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
}
reset.addEventListener("click", function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener("click", function() {
textarea.focus();
})
textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);
{{ EmbedLiveSample('Playable_code', 700, 360) }}
当你需要获得更多的文本细节时,下面的方法可以给你测量文本的方法。
下面的代码段将展示如何测量文本来获得它的宽度:
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var text = ctx.measureText("foo"); // TextMetrics object
text.width; // 16;
}
在Geoko(Firefox,Firefox OS及基于Mozilla的应用的渲染引擎)中,曾有一些版本较早的 API 实现了在canvas上对文本作画的功能,但它们现在已不再使用。
{{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}