HTML Canvas 文字顏色
HTML Canvas 文字顏色
要設定 Canvas 上的文字顏色,我們使用兩個屬性:
-
fillStyle
- 定義文字的填充顏色 -
strokeStyle
- 定義文字輪廓的顏色
fillStyle 屬性
fillStyle
屬性定義了文字的填充顏色。
示例
將字型設定為 50px "Arial"。將填充顏色設定為紫色。在 Canvas 上寫入填充文字。從位置 (10,80) 開始。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "50px Arial";
ctx.fillStyle = "purple";
ctx.fillText("Hello World",10,80);
</script>
自己動手試一試 »
strokeStyle 屬性
strokeStyle
屬性定義了文字輪廓的顏色。
示例
將字型設定為 50px "Arial"。將輪廓顏色設定為紫色。在 Canvas 上寫入輪廓文字。從位置 (10,80) 開始。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "50px Arial";
ctx.strokeStyle = "purple";
ctx.strokeText("Hello World",10,80);
</script>
自己動手試一試 »
用漸變填充文字
示例
這裡我們用漸變填充文字。
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// 建立線性漸變
const grad=ctx.createLinearGradient(0,0,280,0);
grad.addColorStop(0, "lightblue");
grad.addColorStop(1, "darkblue");
// 用漸變填充文字
ctx.font = "50px Arial";
ctx.fillStyle = grad;
ctx.fillText("Hello World",10,80);
</script>
自己動手試一試 »
用漸變填充輪廓文字
示例
這裡我們用漸變填充輪廓文字。
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// 建立線性漸變
const grad=ctx.createLinearGradient(0,0,280,0);
grad.addColorStop(0, "lightblue");
grad.addColorStop(1, "darkblue");
// 用漸變填充輪廓文字
ctx.font = "50px Arial";
ctx.strokeStyle = grad;
ctx.strokeText("Hello World",10,80);
</script>
自己動手試一試 »