更改 "screen" 波浪的颜色

Change the color of the "screen" waves

我一直坚持让波浪看起来像我想要的那样。我想弄清楚如何让波浪的底部成为我需要的颜色。我可以做我想要的颜色,但它会阻挡背景。我看不到它背后的任何东西,因为我像在反射一样使用。也许有人能弄明白,因为我很难让它发挥作用……我计划让波浪起伏。这里有一个link给码笔:HERE

这是我有垂直反射的地方:

var x = $.cx - $.length / 2 + $.length / $.count * i,
    y = height + $.simplex.noise2D($.xoff, $.yoff) * amp + sway;
    $.ctx[i === 0 ? 'moveTo' : 'lineTo'](x, y);
  }

  $.ctx.lineTo($.w, $.h); // -$.h - Vertically reflection
  $.ctx.lineTo(0, $.h); // -$.h - Vertically reflection
  $.ctx.closePath();
  $.ctx.fillStyle = color;

  if (comp) {
    $.ctx.globalCompositeOperation = comp;
  }

  $.ctx.fill();

我想要的波浪外观如下:

这是我得到的成功的透明顶部,只是颜色不对:

你的问题是三种颜色的 screen 混合产生纯白色,所以你的 canvas 的所有底部都变成白色。

这里我把情况简化了很多,只有3个矩形。你的canvas底部是我中间的白色方块:

const c2 = canvas.cloneNode();

const ctx = canvas.getContext("2d");

ctx.globalCompositeOperation = 'screen';
ctx.fillStyle = '#fb0000';
ctx.fillRect(0,0,50,50);
ctx.fillStyle = "#00ff8e";
ctx.fillRect(12,12,50,50);
ctx.fillStyle = "#6F33FF";
ctx.fillRect(25,25,50,50);
body {
  background: #CCC;
}
<canvas id="canvas"></canvas>

所以我们需要的是一种使这个中央正方形透明的方法,以便我们可以在后面绘制背景。

为此,我们至少需要绘制两次形状:

  • 在正常合成模式下一次,以便我们获得完全重叠。
  • 再次作为 source-in 合成模式,这样我们就可以只得到所有形状重叠的地方。

const ctx = canvas.getContext("2d");

function drawShapes(mode) {
  ctx.globalCompositeOperation = mode;
  ctx.fillStyle = '#fb0000';
  ctx.fillRect(0,0,50,50);
  ctx.fillStyle = "#00ff8e";
  ctx.fillRect(12,12,50,50);
  ctx.fillStyle = "#6F33FF";
  ctx.fillRect(25,25,50,50);
}

drawShapes('screen');
drawShapes('source-in');
body {
  background: #CCC;
}
<canvas id="canvas"></canvas>

现在我们有了重叠区域,我们可以在第三次操作中将其用作切割形状。但要做到这一点,我们需要第二个离屏 canvas 来执行两种状态的合成:

const c2 = canvas.cloneNode();

const ctx = canvas.getContext("2d");
const ctx2 = c2.getContext("2d");

function drawShapes(ctx, comp) {
  ctx.globalCompositeOperation = comp;
  ctx.fillStyle = '#fb0000';
  ctx.fillRect(0, 0, 50, 50);
  ctx.fillStyle = "#00ff8e";
  ctx.fillRect(12, 12, 50, 50);
  ctx.fillStyle = "#6F33FF";
  ctx.fillRect(25, 25, 50, 50);
}
// first draw our screen, with unwanted white square
drawShapes(ctx, 'screen');
// draw it on the offscreen canvas
ctx2.drawImage(ctx.canvas, 0, 0)
// draw the shapes once again on the offscreen canvas to get the cutting shape
drawShapes(ctx2, 'source-in');
// cut the visible canvas
ctx.globalCompositeOperation = 'destination-out'
ctx.drawImage(ctx2.canvas, 0, 0);
body {
  background: #CCC
}
<canvas id="canvas"></canvas>

瞧,我们的白色方块现在是透明的,我们可以使用 destination-over 复合操作在场景后面绘制任何我们想要的东西。