简体   繁体   中英

Javascript and Canvas Draw Circle with Hole in Middle

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 found this solution http://jsfiddle.net/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM