選單
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

HTML Canvas 填充和描邊


Canvas 填充和描邊

要為 canvas 中的形狀/物件定義填充顏色和輪廓顏色,我們使用以下屬性:

屬性 描述
fillStyle 定義物件/形狀的填充顏色
strokeStyle 定義物件/形狀輪廓的顏色

fillStyle 屬性

fillStyle 屬性定義物件的填充顏色。

fillStyle 屬性的值可以是顏色(顏色名稱、RGB、HEX、HSL)、漸變或圖案。

示例

抱歉,您的瀏覽器不支援 canvas。

將填充顏色設定為“綠色”,並使用 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)、漸變或圖案。

示例

抱歉,您的瀏覽器不支援 canvas。

將輪廓顏色設定為“藍色”,並使用 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

組合上面的兩個矩形是完全合法的。

示例

抱歉,您的瀏覽器不支援 canvas。
<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

你也可以為 fillStylestrokeStyle 屬性新增 Alpha 通道,以建立不透明度。

示例

抱歉,您的瀏覽器不支援 canvas。

fillStylestrokeStyle 屬性的不透明度設定為 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>
自己動手試一試 »

×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援