gpt4 book ai didi

javascript - 更改 "screen"波浪的颜色

转载 作者:行者123 更新时间:2023-11-30 14:11:57 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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>

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

关于javascript - 更改 "screen"波浪的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com