fillText() 是 Canvas 2D API 在 (x, y)位置填充文本的方法。如果選項(xiàng)的第四個參數(shù)提供了最大寬度,文本會進(jìn)行縮放以適應(yīng)最大寬度。
使用 fillText(),在畫布上使用漸變寫文本 "菜鳥教程!" 和 "(cainiaoplus.com)!":
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML canvas fillText() 方法使用-菜鳥教程(cainiaoplus.com)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的瀏覽器不支持 HTML5 canvas 標(biāo)簽。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Georgia";
ctx.fillText("菜鳥教程!",10,50);
ctx.font="30px Verdana";
// 創(chuàng)建一個漸變
var 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("(cainiaoplus.com)!",10,90);
</script>
</body>
</html>測試看看 ?/?IEFirefoxOperaChromeSafari
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 fillText() 方法。
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
注意:Safari 不支持 maxWidth 參數(shù)。
fillText() 方法在畫布上繪制填充的文本。文本的默認(rèn)顏色是黑色(#000000)。
提示:請使用 font 屬性來定義字體和字號,并使用 fillStyle 屬性以另一種顏色/漸變來渲染文本。
| JavaScript 語法: | context.fillText(text,x,y,maxWidth); |
|---|
| 參數(shù) | 描述 |
|---|---|
| text | 規(guī)定在畫布上輸出的文本。 |
| x | 開始繪制文本的 x 坐標(biāo)位置(相對于畫布)。 |
| y | 開始繪制文本的 y 坐標(biāo)位置(相對于畫布)。 |
| maxWidth | 可選。允許的最大文本寬度,以像素計(jì)。 |