画布中圆弧的不同填充颜色

26

我想这个问题的解决方案非常简单,如果这显而易见,那么我提前道歉,但是我似乎无法找出如何为两个不同的弧设置两个不同的fillStyles ...我只想能够绘制不同颜色的圆。下面是我通常在画布中使用其他形状/绘图方法时所做的方式,但是由于某些原因,在弧上它将两个弧都设置为最后一个fillStyle。

ctx.fillStyle = "#c82124"; //red
ctx.arc(15,15,15,0,Math.PI*2,true);
ctx.fill();

ctx.fillStyle = "#3370d4"; //blue
ctx.arc(580,15,15,0,Math.PI*2,true);
ctx.fill();
3个回答

52

我认为你可能遗漏了路径的开始和结束语句。尝试使用以下代码(它在我的jsfiddle中有效,可以在这里看到

ctx.fillStyle = "#c82124"; //red
ctx.beginPath();
ctx.arc(15,15,15,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();

ctx.fillStyle = "#3370d4"; //blue
ctx.beginPath();
ctx.arc(580,15,15,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();

啊,当然!!!我想这肯定是显而易见的事情。由于某种原因,我认为只有在绘制线条或曲线时才需要begin/closePath,但我猜它总是必要的 :) 非常感谢! - Nick Briz
1
在这里,ctx.closePath()是无用的。它所做的是将当前子路径封闭起来,即从当前路径位置到上一个打开点绘制一条线。fill()已经完成了这个过程。只需要beginPath() - Kaiido

0
请注意,路径只是几何形状。您可以在fill( )之前随时设置.fillStyle

-1

我使用了beginPath()函数,它有效了。希望这些方法对你也有效:

ctx.fillStyle = "#c82124"; //red
ctx.beginPath();
ctx.arc(15,15,15,0,Math.PI*2,true);
ctx.fill();
ctx.fillStyle = "#3370d4"; //blue
ctx.beginPath();
ctx.arc(580,15,15,0,Math.PI*2,true);
ctx.fill();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接