对于矩形轮廓,您必须计算片段与轮廓的绝对值:
float smoothedAlpha =
1.0 - smoothstep(-edgeSoftness, edgeSoftness, abs(distance) - thickness);
完整的shaderoy着色器(2D 圆角矩形轮廓 https://www.shadertoy.com/view/7tsXRN):
// from http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
float roundedBoxSDF(vec2 CenterPosition, vec2 Size, float Radius)
{
return length(max(abs(CenterPosition)-Size+Radius,0.0))-Radius;
}
void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
vec2 size = vec2(300.0, 200.0);
vec2 location = iMouse.xy;
float thickness = 5.0;
float shadowSoftness = 30.0f;
vec2 shadowOffset = vec2(10.0, -10.0);
float edgeSoftness = 1.0;
float radius = (sin(iTime*2.0) + 1.0) * 30.0 + thickness * 2.0;
float distance = roundedBoxSDF(location - fragCoord.xy, size/2.0, radius);
float smoothedAlpha = 1.0 - smoothstep(-edgeSoftness, edgeSoftness, abs(distance) - thickness);
vec4 quadColor = mix(vec4(1.0), vec4(0.0, 0.2, 1.0, smoothedAlpha), smoothedAlpha);
float shadowDistance = roundedBoxSDF(location + shadowOffset - fragCoord.xy, size/2.0, radius);
float shadowAlpha = 1.0 - smoothstep(-shadowSoftness/2.0, shadowSoftness/2.0, abs(shadowDistance));
vec4 shadowColor = vec4(0.4, 0.4, 0.4, 1.0);
fragColor = mix(quadColor, shadowColor, shadowAlpha - smoothedAlpha);
}