--- title: CanvasRenderingContext2D.strokeText() slug: Web/API/CanvasRenderingContext2D/strokeText translation_of: Web/API/CanvasRenderingContext2D/strokeText ---
CanvasRenderingContext2D.strokeText() 是 Canvas 2D API 在给定的 (x, y) 位置绘制文本的方法。如果提供了表示最大值的第四个参数,文本将会缩放适应宽度。
参见 {{domxref("CanvasRenderingContext2D.fillText()")}} 方法填充文本。
void ctx.strokeText(text, x, y [, maxWidth]);
textxymaxWidth {{optional_inline}}strokeText 方法这是一个使用 strokeText 方法的简单的代码片段。
<canvas id="canvas"></canvas>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "48px serif";
ctx.strokeText("Hello world", 50, 100);
修改下面的代码并在线查看 canvas 的变化:
<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.strokeText("Hello world", 50, 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) }}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-stroketext", "CanvasRenderingContext2D.strokeText")}} | {{Spec2('HTML WHATWG')}} |