strokeStyle() 不改变 fillRect() 的颜色

strokeStyle() not changing color for fillRect()

所以我有一个canvas。我想绘制多个不同颜色的填充矩形。

实际代码非常冗长,并且有层层依赖。这是相关部分:

var c=document.getElementById("result"); //result is a canvas object
var cnv=c.getContext("2d");
cnv.beginPath();
cnv.strokeStyle="#00F000"; //coloring it green
cnv.moveTo(x,y);  //moving to a specific point on the canvas
cnv.fillRect(x,y,3,33);  //drawing a filled rectangle
cnv.stroke();
cnv.closePath();

如果我提醒(cnv.strokeStyle);它确实显示颜色已设置为 00F000 并且它也在绘制矩形。唯一的问题是所有的图纸都是默认的(黑色)颜色。

我做错了什么?

改用fillStyle

var c=document.getElementById("result"); //result is a canvas object
var cnv=c.getContext("2d");
cnv.beginPath();
cnv.fillStyle="#00F000"; //coloring it green
cnv.moveTo(x,y);  //moving to a specific point on the canvas
cnv.fillRect(x,y,3,33);  //drawing a filled rectangle
cnv.closePath();

CanvasRenderingContext2D fillRect() 方法使用 fillStyle 方法定义的颜色填充区域。

然而,stroke() 方法使用由 moveTo()lineTo()curveTo()... 设置的颜色填充先前调用定义的路径轮廓strokeStyle() 方法。

在您的代码片段中,没有定义实际路径,因此对 stroke() 的最终调用没有任何结果,您获得的唯一视觉输出是对 fillRect() 的调用,默认为黑色。

如果您希望矩形的轮廓也可见,则必须使用与 fillRect() 相同的参数调用 strokeRect()。

这是一个例子:

var c=document.getElementById("result"); //result is a canvas object
var cnv=c.getContext("2d");
let x=20;
let y=20;
cnv.beginPath();
cnv.strokeStyle="#00F000"; //coloring it green
cnv.moveTo(x,y);  //moving to a specific point on the canvas
cnv.fillRect(x,y,3,33);  //drawing a filled rectangle
cnv.strokeRect(x,y,3,33);
cnv.closePath();
<canvas id="result"></canvas>

如果你想让描边矩形代替填充矩形,那么你必须使用 strokeRect() 而不是 fillRect()。此外,这两者都允许您不必在之后调用 fill()stroke(),因为它们已经这样做了。

如果你要使用 cnv.rect() 那么你需要在之后调用 stroke 或 fill。确保在编写代码时不要混淆使用 strokeRect()fillRect()

此外,您不需要将 moveTo() 与这些方法一起使用。他们已经拥有所需的 x 和 y 谎言输入。最后,矩形不需要 beginPath()closePath(),因为它已经包含了矩形。

var c=document.getElementById("result");
var cnv=c.getContext("2d");
cnv.strokeStyle="#00F000"; //coloring it green
cnv.strokeRect(20,20,30,33);  //drawing a filled rectangle
<canvas id='result'></canvas>

您也可以像这样同时进行

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d")

ctx.strokeStyle = "purple"
ctx.fillStyle = "lightgreen"
ctx.rect(20, 20, 50, 50)
ctx.fill()
ctx.stroke()
<canvas id="canvas"></canvas>