The*_*oth 2 javascript shader glsl fragment-shader three.js
我正在尝试为网站上的图像创建 RGB 偏移效果。我有基本功能,但问题是通道与纹理的 uv 发生偏移。因此,如果图像尺寸不同,则每个图像的偏移量在视觉上并不相同。
这是我的片段着色器。
uniform sampler2D texture;
varying vec2 vUv; // vertex uv
void main() {
vec2 uv = vUv;
float red = texture2D(texture, vec2(uv.x, uv.y - .1)).r;
float green = texture2D(texture, uv).g;
float blue = texture2D(texture, vec2(uv.x, uv.y + .1)).b;
float alpha = texture2D(texture, uv).a;
gl_FragColor = vec4(vec3(red, green, blue), alpha);
}
Run Code Online (Sandbox Code Playgroud)
以及它呈现在页面上的样子。

我将如何在不必传递统一值的情况下标准化 uv 偏移?
传递更多信息(例如偏移量)是正常的
uniform float offset1;
uniform float offset2;
uniform sampler2D texture;
varying vec2 vUv; // vertex uv
void main() {
vec2 uv = vUv;
float red = texture2D(texture, vec2(uv.x, uv.y + offset1)).r;
float green = texture2D(texture, uv).g;
float blue = texture2D(texture, vec2(uv.x, uv.y + offset2)).b;
float alpha = texture2D(texture, uv).a;
gl_FragColor = vec4(vec3(red, green, blue), alpha);
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在 JavaScript 中对此进行调整。例如
const uniforms = {
offset1: { value: 0 },
offset2: { value: 0 },
...
};
...
uniforms.offset1.value = 2 / textureHeight;
uniforms.offset2.value = -2 / textureHeight;
Run Code Online (Sandbox Code Playgroud)
如果是我的话我可能会这样做更多
uniform vec2 channelOffsets[4];
uniform vec4 channelMult[4];
uniform sampler2D texture;
varying vec2 vUv; // vertex uv
void main() {
vec2 uv = vUv;
vec4 channel0 = texture2D(texture, uv + channelOffset[0]);
vec4 channel1 = texture2D(texture, uv + channelOffset[1]);
vec4 channel2 = texture2D(texture, uv + channelOffset[2]);
vec4 channel3 = texture2D(texture, uv + channelOffset[3]);
gl_FragColor =
channelMult[0] * channel0 +
channelMult[1] * channel1 +
channelMult[2] * channel2 +
channelMult[3] * channel3 ;
}
Run Code Online (Sandbox Code Playgroud)
并设置它们
const uniforms = {
channelOffsets: { value: [
new THREE.Vector2(),
new THREE.Vector2(),
new THREE.Vector2(),
new THREE.Vector2(),
]},
channelMults: { value: [
new THREE.Vector4(1, 0, 0, 0),
new THREE.Vector4(0, 1, 0, 0),
new THREE.Vector4(0, 0, 1, 0),
new THREE.Vector4(0, 0, 0, 1),
]},
....
}
...
uniforms.channelOffsets.value[0].y = -2 / textureHeight;
uniforms.channelOffsets.value[2].y = 2 / textureHeight;
Run Code Online (Sandbox Code Playgroud)
举一个不太硬编码的例子。我什至可以使用纹理矩阵而不是偏移量,这将允许旋转和缩放每个通道并将它们与允许交换通道的矩阵组合。