用Canvas绘制矩形(3)
ctx.rect(x, y, width, height)
x,y用于确定矩形左上角在Canvas画布坐标系中的位置;width、height表示宽高
ctx.rect(100, 100, 200, 100);
ctx.stroke();
// ctx.fill();
注意:rect需要结合stroke或fill使用,因为同前面线段一样,rect只是绘制除了一个路径,需要stroke描出这个路径,或使用fill填充矩形。这样矩形才能显示出来
ctx.fillRect(x, y, width, height)
其是rect与fill的结合
ctx.fillRect(100, 100, 200, 100);
相当于既绘制出了路径,又使用fill进行了填充
当然,fillStyle任然可用
ctx.strokeRect(x, y, width, height)
其是rect与stroke的结合
ctx.strokeRect(100, 100, 200, 100);
相当于既绘制出了路径,又使用stroke进行了描绘
当然,strokeStyle任然可用
开启新的路径
fillRect与strokeRect都会自动开启新路径
ctx.strokeStyle = 'orange';
ctx.strokeRect(100, 100, 200, 100);
ctx.strokeStyle = 'purple';
ctx.strokeRect(100, 300, 200, 100);
ctx.strokeStyle = 'red';
ctx.moveTo(100, 450);
ctx.lineTo(300, 450);
ctx.stroke();
上述每一路径都有自己的颜色,而不都是red
ctx.fillStyle = 'orange';
ctx.fillRect(100, 100, 200, 100);
ctx.fillStyle = 'purple';
ctx.fillRect(100, 300, 200, 100);
都有独立的填充色
ctx.clearRect(x, y, width, height)
用于擦除参数指定的矩形区域
ctx.fillStyle = 'orange';
ctx.fillRect(100, 100, 200, 100);
ctx.clearRect(100, 100, 100, 100);
看下一篇——用Canvas绘制圆弧与圆角(4)