HTML Canvas 矩形
HTML Canvas 矩形
在 canvas 中繪製矩形最常用的三種方法是:
rect()
方法fillRect()
方法strokeRect()
方法
rect() 方法
rect()
方法定義一個矩形。
rect()
方法具有以下引數:
引數 | 描述 |
---|---|
x | 矩形左上角的 x 座標 |
y | 矩形左上角的 y 座標 |
width | 矩形的寬度(以畫素為單位) |
height | 矩形的高度(以畫素為單位) |
示例
使用 rect()
定義一個 150*100 畫素的矩形,從位置 (10,10) 開始。然後使用 stroke()
實際繪製矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.rect(10,10, 150,100);
ctx.stroke();
</script>
自己動手試一試 »
請注意,rect()
方法不會繪製矩形(它只定義它)。因此,您還需要使用 stroke()
方法(或 fill()
方法)來實際繪製它。
fillRect() 方法
fillRect()
方法繪製一個填充矩形。
fillRect()
方法具有以下引數:
引數 | 描述 |
---|---|
x | 矩形左上角的 x 座標 |
y | 矩形左上角的 y 座標 |
width | 矩形的寬度(以畫素為單位) |
height | 矩形的高度(以畫素為單位) |
填充顏色透過 fillStyle
屬性指定。如果未設定 fillStyle
屬性,則預設填充顏色為黑色。
示例
使用 fillRect()
繪製一個從位置 (10,10) 開始的填充 150*100 畫素矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillRect(10,10, 150,100);
</script>
自己動手試一試 »
示例
使用 fillStyle
屬性設定填充顏色。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "pink";
ctx.fillRect(10,10, 150,100);
</script>
自己動手試一試 »
strokeRect() 方法
strokeRect()
方法繪製一個帶描邊的(輪廓)矩形。
strokeRect()
方法具有以下引數:
引數 | 描述 |
---|---|
x | 矩形左上角的 x 座標 |
y | 矩形左上角的 y 座標 |
width | 矩形的寬度(以畫素為單位) |
height | 矩形的高度(以畫素為單位) |
描邊顏色透過 strokeStyle
屬性指定。如果未設定 strokeStyle
屬性,則預設描邊顏色為黑色。
示例
使用 strokeRect()
繪製一個從位置 (10,10) 開始的帶描邊的 150*100 畫素矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeRect(10,10, 150,100);
</script>
自己動手試一試 »
示例
使用 strokeStyle
屬性設定輪廓的顏色。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.strokeRect(10,10, 150,100);
</script>
自己動手試一試 »
更多示例
示例
使用 rect()
方法建立三個矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 紅色矩形
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(5, 5, 290, 140);
ctx.stroke();
// 綠色矩形
ctx.beginPath();
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.rect(30, 30, 50, 50);
ctx.stroke();
// 藍色矩形
ctx.beginPath();
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.rect(50, 50, 150, 80);
ctx.stroke();
</script>
自己動手試一試 »
示例
使用 strokeRect()
方法,用更少的程式碼獲得與上面相同的結果。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 紅色矩形
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.strokeRect(5, 5, 290, 140);
// 綠色矩形
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.strokeRect(30, 30, 50, 50);
// 藍色矩形
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.strokeRect(50, 50, 150, 80);
</script>
自己動手試一試 »