HTML Canvas 填充和描邊
Canvas 填充和描邊
要為 canvas 中的形狀/物件定義填充顏色和輪廓顏色,我們使用以下屬性:
屬性 | 描述 |
---|---|
fillStyle |
定義物件/形狀的填充顏色 |
strokeStyle |
定義物件/形狀輪廓的顏色 |
fillStyle 屬性
fillStyle
屬性定義物件的填充顏色。
fillStyle
屬性的值可以是顏色(顏色名稱、RGB、HEX、HSL)、漸變或圖案。
示例
將填充顏色設定為“綠色”,並使用 fillRect()
方法繪製一個填充的矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10,10, 100,100);
</script>
自己動手試一試 »
strokeStyle 屬性
strokeStyle
屬性定義輪廓的顏色。
strokeStyle
屬性的值可以是顏色(顏色名稱、RGB、HEX、HSL)、漸變或圖案。
示例
將輪廓顏色設定為“藍色”,並使用 strokeRect()
方法繪製一個帶輪廓的矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
自己動手試一試 »
組合 fillStyle 和 strokeStyle
組合上面的兩個矩形是完全合法的。
示例
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 填充的矩形
ctx.fillStyle = "green";
ctx.fillRect(10,10, 100,100);
// 輪廓矩形
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
自己動手試一試 »
帶 Alpha 通道的 fillStyle 和 strokeStyle
你也可以為 fillStyle
和 strokeStyle
屬性新增 Alpha 通道,以建立不透明度。
示例
將 fillStyle
和 strokeStyle
屬性的不透明度設定為 50%
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 填充的矩形
ctx.fillStyle = "rgb(0 255 0 / 50%)";
ctx.fillRect(10,10, 100,100);
// 輪廓矩形
ctx.strokeStyle = "rgb(0 0 255 / 50%)";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
自己動手試一試 »