different fillStyle colors for arc in canvas
Asked Answered
I

3

26

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();
Intemerate answered 18/12, 2011 at 4:1 Comment(0)
S
52

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

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();
Sigmund answered 18/12, 2011 at 4:7 Comment(2)
Ah, of course!!! I figured it be something as obvious as that. For some reason I thought you only needed begin/closePath when you are drawing lines or curves, but I guess it's always necessary :) thnx so much!Intemerate
ctx.closePath() is useless here. What it does is to enclose the current subpath, i.e it draws a line from the current path position to the last opened point. fill() already does that. Only beginPath() is needed.Micro
M
0

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

Milker answered 6/7, 2015 at 5:26 Comment(0)
O
-1

I tried it with the beginPath() function and it worked. I hope these works for you to:-

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();
Oxfordshire answered 7/10, 2020 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.