更改“屏幕”波浪的颜色

时间:2019-01-21 03:15:21

标签: javascript user-interface canvas html2canvas

我一直坚持让波浪看起来像我想要的那样。我正在尝试弄清楚如何使波的基数成为我需要的颜色。我可以做我想要的颜色,但是会挡住背景。我看不到它背后的任何东西,因为我像反射一样使用。也许有人可以弄清楚,因为我在使其工作上遇到困难...我计划使波浪起伏上升。这是代码笔的链接: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();

我想要的波浪外观如下:

The way I want it to look

这是我获得成功的透明顶部的原因,只是颜色不正确: Not my desired look

1 个答案:

答案 0 :(得分:2)

您的问题是三种颜色的screen混合会产生纯白色,因此画布的所有底部都变成白色。

在这里,我仅用3个矩形就简化了很多情况。您的画布底部是我中央的白色方块:

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>

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

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>

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

相关问题