Task
Using the
mixfunction create a linear gradient that transitions from a givencolor1tocolor2. Use thexnormalized coordinate of the pixel as the interpolation factor. Apply thestepfunction so that color transition starts from position0.25and ends at1.0.
使用mix函数创建一个从color1到color2线性渐变的过渡颜色。使用x像素的标准化坐标作为插值因子。并且使用step函数来获取线性过渡的开始位置和结束位置[0.25, 1.0]。
Theory
mix函数用于基于第三个插值因子在两个值之间执行线性插值。此函数通常用于着色器中,以平滑过渡两个值,例如颜色、位置或其他属性。
函数
T mix(T start, T end, T t)
该mod函数有三个参数:
start: 开始值end: 结束值t: 插值因子
插值因子说明
- 当
t等于0,结果等于start。 - 当
t等于1, 结果等于end。 - 当
t介于0和1之间时,结果是start和end之间的线性插值。
示例
颜色插值:
scss
vec3 color1 = vec3(1.0, 0.0, 0.0); // red color
vec3 color2 = vec3(0.0, 0.0, 1.0); // blue color
float factor = 0.5; // interpolation factor
// result will be a purple color (halfway between red and blue)
vec3 resultColor = mix(color1, color2, factor);
在两个位置之间进行插值:
ini
vec3 position1 = vec3(0.0, 0.0, 0.0);
vec3 position2 = vec3(1.0, 1.0, 1.0);
float factor = 0.3;
// result will be a position 30% of the way from position1 to position2
vec3 interpolatedPosition = mix(position1, position2, factor);
Answer
glsl
uniform vec2 iResolution;
void main() {
// Normalized pixel coordinates (from 0 to 1)
vec2 uv = gl_FragCoord.xy / iResolution.xy;
vec3 color2 = vec3(0.38, 0.12, 0.93);
vec3 color1 = vec3(1.00, 0.30, 0.30);
float xrang = step(0.25, uv.x);
vec3 color = mix(color1, color2, xrang * (uv.x - 0.25) / 0.75);
gl_FragColor = vec4(color, 1.0);
}
效果

练习
最后
如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!