首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >HTML5 Canvas - fillRect() vs rect()

HTML5 Canvas - fillRect() vs rect()
EN

Stack Overflow用户
提问于 2014-03-21 21:04:05
回答 2查看 23K关注 0票数 20

在下面的代码中,如果我在两个地方使用rect()fill(),第二个fillStyle会覆盖第一个中指定的颜色(即,两个矩形都是绿色的),但如果我将第一个矩形改为fillRect(),则第二个矩形将按预期工作(即,第一个矩形为蓝色,第二个矩形为绿色)。为甚麽呢?我以为fillRect()只是rect(),然后是fill(),对吧?

代码语言:javascript
复制
ctx.translate(canvas.width/2, canvas.height/2);

ctx.fillStyle = "#5A9BDC";
ctx.fillRect(0, 0, rectWidth, rectHeight);
// ctx.rect(0, 0, rectWidth, rectHeight);
// ctx.fill();    

ctx.translate(-canvas.width/2, -canvas.height/2);

ctx.fillStyle = "#31B131";
ctx.rect(0, 0, rectWidth, rectHeight);
ctx.fill();

在Chrome | Fiddle中测试

EN

回答 2

Stack Overflow用户

发布于 2014-03-21 22:30:24

据我所知,canvas有3个"rect“函数:fillRectstrokeRectrect

代码语言:javascript
复制
ctx.rect(0,0,rectWidth,rectHeight); // create some shape, there is nothing on the canvas yet
ctx.stroke(); // draw stroke of the shape
ctx.fill();   // fill the shape

有两个快捷键:

代码语言:javascript
复制
ctx.strokeRect(0,0,rectWidth,rectHeight); // shortcut to stroke rectangle
ctx.fillRect(0, 0, rectWidth, rectHeight); // shortcut to fill rectangle

因此,您的fill调用只能填充使用rect创建的形状。

票数 5
EN

Stack Overflow用户

发布于 2020-10-27 18:49:55

如果要为不同的路径命令使用不同的颜色,请在每个命令生效之前调用beginPath()

代码语言:javascript
复制
ctx.beginPath();  
ctx.fillStyle="red";
ctx.rect(10,10,10,10);
ctx.fill()

ctx.beginPath()
ctx.fillStyle="green";
ctx.rect(20,20,10,10);  
ctx.fill()

ctx.beginPath()
ctx.fillStyle="blue";  
ctx.rect(30,30,10,10);  
ctx.fill()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22559603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档