Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different fillStyle colors for arc in canvas

Tags:

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(); 
like image 410
Nick Briz Avatar asked Dec 18 '11 04:12

Nick Briz


People also ask

How do I change the color of my element in canvas?

In a sense, you can't really "change" the color of an element on the canvas because it has no scene graph, or, in other words, it has no history of what has been drawn on the canvas. To change the color of a line, you would have to redraw the line. ctx. moveTo(0, 0); ctx.

How do I fill a rectangle with canvas color?

The fillRect() method draws a "filled" rectangle. The default color of the fill is black. Tip: Use the fillStyle property to set a color, gradient, or pattern used to fill the drawing.

How do you fill a canvas with HTML color?

The fill() method fills the current drawing (path). The default color is black. Tip: Use the fillStyle property to fill with another color/gradient.


2 Answers

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(); 
like image 88
puk Avatar answered Sep 23 '22 04:09

puk


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

like image 30
Tim Erickson Avatar answered Sep 26 '22 04:09

Tim Erickson