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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8549725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:28:13  来源:igfitidea点击:

different fillStyle colors for arc in canvas

javascriptcanvascolorsfillgeometric-arc

提问by Nick

I imagine the solution to this is very simple, and apologize in advance if this is painfully obvious, but I can't seem to figure out how to set two different fillStyles for two different arcs ...I just wanna be able to draw different color circles. Below I have how I would normally do it with other shapes/drawing methods in canvas, but for some reason with arcs it sets both arcs to the last 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();

回答by puk

I think you're missing the begin and end path statements. Try the following (it works for me in jsfiddle, see here)

我认为您缺少开始和结束路径语句。尝试以下操作(它在 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();

回答by Tim Erickson

Note that the path is just the geometry. You can set .fillStyleanytime up until the fill( ).

请注意,路径只是几何图形。您可以.fillStyle随时进行设置,直到fill( ).