JS Canvas - 填充豆形多边形

JS Canvas - Filling a bean-shaped polygon

我在使用 JS canvas ctx.fill() 填充多边形外部时遇到问题。

我的代码是这样工作的:

ctx.beginPath()
// Here are for loops that draws a the closed shape using
ctx.stroke();
ctx.fill();

这是 for 循环:

var sx1, sy1, ex1, ey1, sx2, sy2, ex2, ey2;
for(var i = 0; i < n; i += Math.floor(n/steps)){
 var radius = Math.exp(-2*i/n)*rmax+rmin;
 radius += frequencyData[i]/255*(n-i + 200)/n*50;
 var angle = -Math.PI/2 - i/n*2*Math.PI;
 var x = radius*Math.cos(angle) + w/2+rmin/2;
 var y = radius*Math.sin(angle) + (h-110)/2+rmin/2 + analyser_offset;

 if (i == 0) {
   gctx.moveTo(x,y);
   sx1 = x;
   sy1 = y;
 }else if (i == n-1){
   ex1 = x;
   ey1 = y;
 }else{
   gctx.lineTo(x,y);
 }

 spd += frequencyData[i];
}
for(var i = 0; i < n; i += Math.floor(n/steps)){
 var radius = Math.exp(-2*i/n)*rmax+rmin;
 radius -= frequencyData[i]/255*(n-i + 200)/n*50;
 var angle = -Math.PI/2 - i/n*2*Math.PI;
 var x = radius*Math.cos(angle) + w/2+rmin/2;
 var y = radius*Math.sin(angle) + (h-110)/2+rmin/2 + analyser_offset;

 if (i == 0) {
   gctx.moveTo(x,y);
 }else if (i == 20){
   sx2 = x;
   sy2 = y;
 }else if (i == n-1){
   ex2 = x;
   ey2 = y;
 } else {
   gctx.lineTo(x,y);
 }
}
gctx.moveTo(sx1, sy1);
gctx.lineTo(sx2, sy2);
gctx.moveTo(ex1, ey1);
gctx.lineTo(ex2, ey2);

所以第一个 for 循环绘制形状的外侧,第二个 for 循环绘制形状的内侧。然后 sx1, sy1, ex1, ey1, sx2, sy2, ex2, ey2 变量在这里以确保在最后 4 行中,它关闭了形状(通过在外线和内线之间添加垂直线)。也许出现这个问题是因为我以不寻常的顺序画线? (就像从 2 条水平线开始然后添加 2 条垂直线来绘制一个矩形) 这是我在 fill() 之后得到的:

这就是我想要的:

那么你能指导我如何实现这一目标吗?

好的,我通过使第二个循环按如下相反的顺序进行修复来修复它:for (var i = n-1; i >= 0; i -= Math.floor(n/steps)) 所以它以更常见的顺序绘制多边形并且有效!我什至不需要使用我想要的最后 4 行来关闭它,这太棒了!