You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GLSL片段着色器中填充正弦曲线下方的区域

实现方案

核心修改思路

原来的代码仅检测像素是否落在正弦曲线的线条上,仅将线条本身设为COLOR1。要填充曲线下方区域,只需将判断条件改为检测当前像素是否位于曲线的下方区域即可。

修改后的完整代码

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform float u_time;

const float AMPLITUDE = 0.125;
const float PERIOD = 1.0;
const float VELOCITY = 8.0;

const vec3 COLOR1 = vec3(1.0, 0.5, 0.0);
const vec3 COLOR2 = vec3(1.0, 0.0, 0.0);

#define PI 3.141592653589793
#define TWO_PI 6.283185307179586

void main() {
    vec2 uv = gl_FragCoord.xy / u_resolution;
    
    float phase = u_time * VELOCITY / PI;
    float curve = AMPLITUDE * sin(uv.x * TWO_PI / PERIOD - phase);

    // 替换原来的shape计算逻辑:判断当前像素是否在曲线下方
    float curveY = 0.5 - curve;
    float shape = step(uv.y, curveY);
    
    // 可选:如果需要填充区域边缘抗锯齿,替换为下面这行
    // float shape = 1.0 - smoothstep(curveY - 2.0/u_resolution.y, curveY, uv.y);
    
    vec3 color = (1.0 - shape) * COLOR2 + shape * COLOR1;
    gl_FragColor = vec4(color, 1.0);
}

改动说明

  • 原来的shape计算使用distance判断像素到曲线的距离,仅匹配线条上的像素
  • 新逻辑先计算当前x坐标对应的正弦曲线y轴位置curveY,再用step判断当前像素的uv.y是否小于等于curveY,所有符合条件的像素都会被标记为填充区域
  • 可选的抗锯齿方案使用smoothstep做2像素的渐变过渡,避免填充边缘出现锯齿

内容的提问来源于stack exchange,提问作者Ariel Malka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:06:03