GLSL shader learning series 2 - draw a circle

This is the second article of the GLSL shader learning series. In this article, we will learn how to use the shader to draw a circle.

Primer

The content of the previous article is relatively simple and easy to understand. Since gl_FragCoordit can represent the coordinates of each pixel in the canvas, it is easy to obtain the effect of continuous gradient through normalization. So, how to use the shader to draw a circle with a clear sense of border? Here you need to use stepa function, its function is similar to a filter, set the value greater than the threshold to 1, and set the value smaller than the threshold to 0. See the sample code below:

#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;

void main() {
    vec2 st = gl_FragCoord.xy / u_resolution;
    
    // 如果st.x的值小于等于0.5, stepX的取值为0,否则为1
    float stepX = step(0.5, st.x);

    // gl_FragColor的取值可能为vec4(0., 0., 0., 1.)或vec4(1.,0.,0.,1.)
    gl_FragColor=vec4(stepX, 0., 0.0, 1.0);
}

With the help of step, we have been able to draw a well-defined image!

draw a circle

In addition to stepfunctions, functions are also needed lengthto draw a circle (more shader functions can be read in this blog ). lengthThe function returns the length of the vector, eg length(vec2(1,0))evaluates to 1.

At this point, if you have elementary school mathematics foundation, you should be able to draw a circle, no more explanation:

#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;

void main(){
    // 减去0.5是为了让圆心在画布中央
    vec2 st=gl_FragCoord.xy/u_resolution - 0.5;
    
    // 计算任何一个像素点距离原点坐标的距离
    float r = length(st);
    float s = step(.4, r);
    
    // gl_FragColor的取值可能为vec4(0., 0., 0., 1.)或vec4(1.,1.,1.,1.)
    gl_FragColor=vec4(s, s, s, 1.);
}

insert image description here

Guess you like

Origin blog.csdn.net/qq_26822029/article/details/129252404