user3797449
user3797449

Reputation: 35

HTML5 canvas how to split circle to X parts

I need split circle to X parts without white center

I have already this code: http://jsfiddle.net/U2tPJ/78/ I get this result:

enter image description here

I need finish result like this (without white center):

enter image description here

Upvotes: 0

Views: 4283

Answers (2)

GameAlchemist
GameAlchemist

Reputation: 19294

Since what you want is to fill a part of the circle, use fill(), not stroke().

• The shape you want to draw (a pie) starts in the circle center :

ctx.moveTo(x,y);

Then follow the arc :

 context.arc(x, y, radius, i*pieAngle, (i+1)*pieAngle, false);

Then fill().

• Notice that the segmentDepth you were using was in fact an angle in degree. To clarify i used :

// size of a pie : it is an angle in radians
var pieAngle = 2 * Math.PI / hours;

• Lastly i used hsl colors to easily get a bunch of colors different for each hour :

    var hueValue = i * 15;
    context.fillStyle = 'hsl(' + hueValue + ',70%, 60%)';

result look this way :

enter image description here

draw code

function drawSegments(radius) {
    for (var i = 0; i < hours; i++) {
        context.beginPath();
        context.moveTo(x, y);
        context.arc(x, y, radius, i*pieAngle, (i+1)*pieAngle, false);
        context.lineWidth = segmentDepth;
        var hueValue = i * 15;
        context.fillStyle = 'hsl(' + hueValue + ',70%, 60%)';
        // '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        context.fill();
        context.lineWidth = 2;
        context.strokeStyle = '#444';
        context.stroke();
    }
}

fiddle : http://jsfiddle.net/gamealchemist/U2tPJ/79/

Upvotes: 5

Philipp
Philipp

Reputation: 69683

The width of the ring is controlled by the line context.lineWidth = segmentDepth;. It seems like you forgot that the line width goes into both directions. To make the ring go to the center, change it to segmentDepth * 2. However, this will also make the whole graphic twice as big, so you might want to compensate by reducing the segmentDepth.

Upvotes: 2

Related Questions