简体   繁体   English

使用html5画布绘制一个切边的圆圈

[英]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. 我的第一种方法是画一个笔画圈并在两侧做clearRect--但是我想让它们中的许多相邻,我不能清楚画布上已经绘制的内容。

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 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. clip() method使用当前定义的路径剪切下一个绘制的图形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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