用Canvas绘制矩形(3)

本文介绍了如何使用HTML5 Canvas API进行矩形绘制,包括ctx.rect()、ctx.fillRect()、ctx.strokeRect()方法的使用,以及如何清除矩形区域。同时强调了rect方法需要结合stroke或fill才能显示矩形。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值