矩形
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 | 矩形的高度。 |