Bharathi
Bharathi

Reputation: 1328

draw donut path using canvas element

I want to draw a dounut path using canvas. It contains the inner and outer arch connecting with line. But I am getting wrongly canvas image. Please see the below image.

enter image description here

Expected:

enter image description here

This is my code.

 this.ctx.beginPath();
 this.ctx.moveTo(options.x, options.y);
 this.ctx.arc(options.x, options.y, options.radius, options.start, options.end, false);
 this.ctx.lineTo(options.x, options.y);
 this.ctx.arc(options.x, options.y, options.innerR, options.start, options.end, false);
 this.ctx.closePath();

Anyone please help me to solve this issue.

Thanks, Bharathi.

Upvotes: 1

Views: 401

Answers (2)

Roshan
Roshan

Reputation: 2184

I have done it using css

        var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
        gradient.addColorStop(0, "#008B8B");
        gradient.addColorStop(0.75, "#F5DEB3");
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

Just remove the last two lines from my above code you will see that the inner circle appears again

SEE DEMO HERE

Upvotes: 0

Dr. Pee
Dr. Pee

Reputation: 126

When moving your "pen" to (options.x, options.y) and then drawing a circle around this point, your "pen" first has to go to the starting position of your arc. Here the line is drawn that you don't want to have on your canvas.

To solve this problem, you have to calculate the starting position of your outer circle (depending on the start angle). You should try with sin or cos to calculate your "new" x and y.

It would then look something like

var newX = options.x + options.radius * cos(options.start);
var newY = options.y + options.radius * sin(options.start);

Then move to this position

this.ctx.moveTo(newX, newY);

And draw the circle around the old x and y

this.ctx.arc(options.x, options.y, options.radius, options.start, options.end, false);

For the inner circle and the end positions you can calculate it similar to this.

Upvotes: 0

Related Questions