## 矩形
canvas提供了4個與矩形相關的方法:
繪制一個填充的矩形
```
fillRect( x ,y ,width, height)
```
例子:canvas-demo/fillRect.html:
```
<canvas id="canvas" width="400" height="300">
不支持canvas
</canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = '';
ctx = canvas.getContext('2d');
ctx.fillRect(10, 10, 80, 80);
</script>
```
繪制一個矩形的邊框
```
strokeRect( x ,y ,width, height)
```
例子:canvas-demo/strokeRect.html:
```
<canvas id="canvas" width="400" height="300">
不支持canvas
</canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = '';
ctx = canvas.getContext('2d');
ctx.strokeRect(10, 10, 80, 80);
</script>
```
上面兩種繪制矩形的方式是直接繪制的,而下面的`rect()`方法有所不同:
```
rect(x, y, width, height)
```
例子:canvas-demo/rect.html:
```
<canvas id="canvas" width="400" height="300">
不支持canvas
</canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = '';
ctx = canvas.getContext('2d');
ctx.rect(10, 10, 80, 80);
ctx.fill();
ctx.rect(100, 100, 80, 80);
ctx.stroke();
</script>
```
注意:`rect()`并不會直接將矩形繪制出來,直到調用`fill()`或`stroke()`方法才會繪制。
`clearRect()`方法的作用類似橡皮擦,清除指定矩形區域,讓清除部分完全透明:
```
clearRect( x ,y ,width, height)
```
例子:canvas-demo/clearRect.html:
```
<canvas id="canvas" width="400" height="300">
不支持canvas
</canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = '';
ctx = canvas.getContext('2d');
ctx.fillRect(10, 10, 80, 80);
ctx.clearRect(20, 20, 30, 30);
ctx.clearRect(60, 60, 10, 10);
</script>
```
四個方法的參數:
| 參數 | 描述 |
| :---: | :---: |
| x | 矩形起始點的 x 軸坐標。 |
| y | 矩形起始點的 y 軸坐標。 |
| width | 矩形的寬度。 |
| height | 矩形的高度。 |