上一 下一

After having seen how to apply styles and colors in the previous chapter, we will now have a look at how to draw text onto the canvas.

绘制文本

The canvas rendering context provides two methods to render text:

fillText(text, x, y [, maxWidth])

Fills a given text at the given (x,y) position. Optionally with a maximum width to draw.

strokeText(text, x, y [, maxWidth])

Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw.

A fillText 范例

The text is filled using the current fillStyle .

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();
			

A strokeText 范例

The text is filled using the current strokeStyle .

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();
			

样式化文本

In the examples above we are already making use of the font property to make the text a bit larger than the default size. There are some more properties which let you adjust the way the text gets displayed on the canvas:

font = value
The current text style being used when drawing text. This string uses the same syntax as the CSS font property. The default font is 10px sans-serif.
textAlign = value
Text alignment setting. Possible values: start , end , left , right or center 。默认值为 start .
textBaseline = value
Baseline alignment setting. Possible values: top , hanging , middle , alphabetic , ideographic , bottom 。默认值为 alphabetic .
direction = value
Directionality. Possible values: ltr , rtl , 继承 。默认值为 继承 .

These properties might be familiar to you, if you have worked with CSS before.

The following diagram from the WHATWG demonstrates the various baselines supported by the textBaseline 特性。 The top of the em square is roughly at the top of the glyphs in a font, the hanging baseline is where some glyphs like आ are anchored, the middle is half-way between the top of the em square and the bottom of the em square, the alphabetic baseline is where characters like Á, ÿ, f, and Ω are anchored, the ideographic baseline is where glyphs like 私 and 達 are anchored, and the bottom of the em square is roughly at the bottom of the glyphs in a font. The top and bottom of the bounding box can be far from these baselines, due to glyphs extending far outside the em square.

A textBaseline example

Edit the code below and see your changes update live in the canvas:

ctx.font = '48px serif';
ctx.textBaseline = 'hanging';
ctx.strokeText('Hello world', 0, 100);
			
Playable code
<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);
			

Advanced text measurements

In the case you need to obtain more details about the text, the following method allows you to measure it.

measureText()
返回 TextMetrics object containing the width, in pixels, that the specified text will be when drawn in the current text style.

The following code snippet shows how you can measure a text and get its width.

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  var text = ctx.measureText('foo'); // TextMetrics object
  text.width; // 16;
}
			

Gecko-specific notes

In Gecko (the rendering engine of Firefox, Firefox OS and other Mozilla based applications), some prefixed APIs were implemented in earlier versions to draw text on a canvas. These are now deprecated and removed, and are no longer guaranteed to work.

上一 下一

元数据

  1. 画布 API
  2. Canvas tutorial
    1. 基本用法
    2. Drawing shapes
    3. Applying styles and colors
    4. 绘制文本
    5. Using images
    6. Transformations
    7. Compositing and clipping
    8. Basic animations
    9. Advanced animations
    10. Pixel manipulation
    11. Hit regions and accessibility
    12. Optimizing the canvas
    13. Finale
  3. 范例
    1. A basic raycaster
    2. Canvas code snippets
    3. Manipulating video using canvas
  4. 接口
    1. HTMLCanvasElement
    2. CanvasRenderingContext2D
    3. CanvasGradient
    4. CanvasPattern
    5. ImageBitmap
    6. ImageData
    7. TextMetrics
    8. Path2D
  5. 文档编制:
  6. 有用清单
    1. Pages tagged "Canvas"
  7. 贡献
    1. Canvas doc status
    2. MDN 工程