Conqueror
Conqueror

Reputation: 4433

Drawing a circle inside another circle canvas

I am trying to draw a gear in Canvas but running into issues from the start. I want to have a filled circle with a hallowed out middle. Instead, I am getting what looks to be an outline of a single circle.

Here is my code:

var ctx = document.getElementById("canvas").getContext("2d"),
i = 0;

function drawGear(){

    ctx.fillStyle = "#000";
    ctx.translate(50,50);
    ctx.arc(0,0,20,0,Math.PI*2);
    ctx.fill();

    ctx.fillStyle = "#FFF";;
    ctx.arc(0,0,5,0,Math.PI*2);
    ctx.fill();
}

drawGear();

http://jsfiddle.net/te3jn/

I believe that the issue is something related to the globalCompositeOperation, but I tried several of them (source-over, source-atop, destination-over) and none seem to work the way I want.

Upvotes: 2

Views: 4818

Answers (1)

raina77ow
raina77ow

Reputation: 106385

You should begin a new path when drawing the second circle, like this:

ctx.fill();

ctx.beginPath();
ctx.fillStyle = "#FFF";
// ... 

JS Fiddle.

Without this, you'll essentially redraw both circles - the inner and the outer one - with the second fill call (check this fiddle for demonstration)

Upvotes: 3

Related Questions