在下面的代码中,如果我在两个地方使用rect()
和fill()
,第二个fillStyle
会覆盖第一个中指定的颜色(即,两个矩形都是绿色的),但如果我将第一个矩形改为fillRect()
,则第二个矩形将按预期工作(即,第一个矩形为蓝色,第二个矩形为绿色)。为甚麽呢?我以为fillRect()
只是rect()
,然后是fill()
,对吧?
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中测试
发布于 2014-03-21 22:30:24
据我所知,canvas有3个"rect“函数:fillRect
、strokeRect
和rect
。
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
有两个快捷键:
ctx.strokeRect(0,0,rectWidth,rectHeight); // shortcut to stroke rectangle
ctx.fillRect(0, 0, rectWidth, rectHeight); // shortcut to fill rectangle
因此,您的fill
调用只能填充使用rect
创建的形状。
发布于 2020-10-27 18:49:55
如果要为不同的路径命令使用不同的颜色,请在每个命令生效之前调用beginPath()
。
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()
https://stackoverflow.com/questions/22559603
复制相似问题