HTML canvas fillText() 方法
實例
使用 fillText(),在畫布上寫文本 "Hello world!" 和 "Big smile!":
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);
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 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 | 可選。允許的最大文本寬度,以像素計。 |
