简体   繁体   中英

Drawing a circle with cut off sides using html5 canvas

I'm trying to draw a circle with cut off sides looking somewhat like this:

切边的圆圈

My first approach was to just draw a stroke-circle and do clearRect on the sides - but I want to render many of these adjacent to each other and I can't afford to clear what's already been drawn on the canvas.

var size = 100;
c.save();
c.strokeStyle = '#ff0000';
c.lineWidth = 50;
c.beginPath();
c.arc(0, 0, size - c.lineWidth / 2, 0, Math.PI * 2);
c.closePath();
c.stroke();

// clear rects on each side to get this effect

c.restore();

Is there a way to limit the arc to not draw further or is there a way to clear on just my little shape somehow and later add it to the main canvas?

I'm not keen on the idea of having multiple canvas elements on top of each other.

Just add a clip mask to it:

DEMO

c.save();

/// define clip    
c.beginPath();
c.rect(120, 120, 160, 160);
c.clip();

/// next drawn will be clipped    
c.beginPath();
c.arc(200, 200, size - c.lineWidth / 2, 0, Math.PI * 2);
c.closePath();
c.stroke();

// clear rects on each side to get this effect
/// and remove clipping mask
c.restore();

The clip() method uses the current defined path to clip the next drawn graphics.

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