HTML5 Canvas - fillRect() vs rect()

HTML5 Canvas - fillRect() vs rect()

本文关键字:rect vs fillRect Canvas HTML5      更新时间:2023-09-26

在下面的代码中,第二个fillStyle覆盖了在第一个指定的颜色,如果我使用rect(),然后在两个地方fill()(即,两个矩形都是绿色的),但工作如预期(即,第一个矩形是蓝色的,第二个是绿色的),如果我改变第一个rect()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

fillRect

。fillRect是一个"独立的"命令,用于绘制和填充矩形。

所以如果你用多个。fillstyle命令发出多个。fillrect命令,每个新的rect将被前面的fillstyle填充。

ctx.fillStyle="red";
ctx.fillRect(10,10,10,10);  // filled with red
ctx.fillStyle="green";
ctx.fillRect(20,20,10,10);  // filled with green
ctx.fillStyle="blue";
ctx.fillRect(30,30,10,10);  // filled with blue

矩形

。Rect是画布路径命令的一部分。

路径命令是组图纸从beginPath()开始,一直持续到发出另一个beginPath()。

在每个组中,只有最后一个样式命令获胜。

所以如果你在一个路径中发出多个。rect命令和多个。fillstyle命令,只有最后一个。fillstyle会被用于所有的。rect。

ctx.beginPath();  // path commands must begin with beginPath
ctx.fillStyle="red";
ctx.rect(10,10,10,10);  // blue
ctx.fillStyle="green";
ctx.rect(20,20,10,10);  // blue
ctx.fillStyle="blue";  // this is the last fillStyle, so it "wins"
ctx.rect(30,30,10,10);  // blue
// only 1 fillStyle is allowed per beginPath, so the last blue style fills all
ctx.fill()

据我所知,画布有3个"rect"函数:fillRect, strokeRectrect

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创建的形状

如果您希望不同路径命令的颜色不同,请在每个命令工作之前调用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()