Latest web development tutorials

HTML canvas fillText() 方法

HTML canvas 參考手冊 HTML canvas參考手冊

實例

使用fillText(),在畫布上寫文本"Hello world!" 和"Big smile!":

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.font="20px Georgia";
ctx.fillText("Hello World!",10,50);

ctx.font="30px Verdana";
// Create gradient
var gradient=ctx.createLinearGradient(0,0,c.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// Fill with gradient
ctx.fillStyle=gradient;
ctx.fillText("Big smile!",10,90);

嘗試一下»

瀏覽器支持

Internet ExplorerFirefoxOperaGoogle ChromeSafari

Internet Explorer 9、Firefox、Opera、Chrome 和Safari 支持fillText() 方法。

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

注意: Safari不支持maxWidth參數。


定義和用法

fillText() 方法在畫布上繪製填色的文本。 文本的默認顏色是黑色。

提示:請使用font屬性來定義字體和字號,並使用fillStyle屬性以另一種顏色/漸變來渲染文本。

JavaScript 語法: context.fillText(text,x,y,maxWidth);

參數值

参数 描述
text 规定在画布上输出的文本。
x 开始绘制文本的 x 坐标位置(相对于画布)。
y 开始绘制文本的 y 坐标位置(相对于画布)。
maxWidth 可选。允许的最大文本宽度,以像素计。


HTML canvas 參考手冊 HTML canvas參考手冊