admin管理员组

文章数量:1327945

I want to draw something like a donut, so a circle with a hole in the middle. I tried using ctx.clip(), but I realized it limits the path to inside, and I want it to limit the path to the outside.

Things to note:
this.lineWidth is how thick the "rim" or the outside portion is

    ctx.beginPath();
    // this should be the hole
    ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
    ctx.clip();
    // this should be the outside part
    ctx.arc(this.x,this.y,this.r+this.lineWidth,0,Math.PI*2,false);
    ctx.fillStyle = "#00ff00";
    ctx.fill();

Instead I'm getting a filled-in circle because it's limiting the path to inside the smaller arc instead of outside it. Is there another method that does the opposite of clip()?

I want to draw something like a donut, so a circle with a hole in the middle. I tried using ctx.clip(), but I realized it limits the path to inside, and I want it to limit the path to the outside.

Things to note:
this.lineWidth is how thick the "rim" or the outside portion is

    ctx.beginPath();
    // this should be the hole
    ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
    ctx.clip();
    // this should be the outside part
    ctx.arc(this.x,this.y,this.r+this.lineWidth,0,Math.PI*2,false);
    ctx.fillStyle = "#00ff00";
    ctx.fill();

Instead I'm getting a filled-in circle because it's limiting the path to inside the smaller arc instead of outside it. Is there another method that does the opposite of clip()?

Share Improve this question asked May 4, 2016 at 22:10 Tyler DaltonTyler Dalton 691 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

I found this solution http://jsfiddle/Hnw6a/:

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

//ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise);  

ctx.beginPath()
ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled)
ctx.arc(100,100,55,0,Math.PI*2, true); // outer (unfills it)
ctx.fill();

With following canvas node:

<canvas id="canvas1" width="500" height="500"></canvas>

Set the linewidth to the desired width, draw your circle, and use "ctx.stroke();". Note that this doesn't allow you to fill the inner circle with a color.

本文标签: Javascript and Canvas Draw Circle with Hole in MiddleStack Overflow