Canvas fillText() 方法
示例
使用 fillText() 在畫布上寫 "Hello world!" 和 "Big smile!" (帶漸變)
JavaScript
const c = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "20px Georgia";
ctx.fillText("Hello World!", 10, 50);
ctx.font = "30px Verdana";
// 建立漸變
const gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// 用漸變填充
ctx.fillStyle = gradient;
ctx.fillText("Big smile!", 10, 90);
自己動手試一試 »
描述
fillText()
方法在畫布上繪製填充文字。
預設的 fillStyle
是 #000000(實心黑)。
另請參閱
font 屬性 (設定文字字型和大小)
fillStyle 屬性 (設定文字顏色/漸變)
textAlign 屬性 (設定文字對齊方式)
textBaseline 屬性 (設定文字基線)
strokeText() 方法 (繪製文字)
語法
context.fillText(text, x, y, maxWidth) |
引數值
引數 | 描述 | 試一試 |
---|---|---|
text | 要寫在畫布上的文字 | 試一試 » |
x | 開始文字的 x 座標 | 試一試 » |
y | 開始文字的 y 座標 | 試一試 » |
maxWidth | (可選) 最大文字寬度(以畫素為單位) | 試一試 » |
返回值
無 |
瀏覽器支援
<canvas>
元素是 HTML5 標準(2014)。
fillText()
在所有現代瀏覽器中都受支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 9-11 |
❮ Canvas 參考