user3578847
user3578847

Reputation: 447

Draw centered circle

I'm trying to figure out how to draw a centered circle using fragment shader. I don't quite understand how to accomplish this. This is what I got so far, but the result is a white screen.

I want to be able to draw it any size and be able to change the offsets as I like (move the circle around).

void main()
{
    float radius        = 10.0;

    float viewWidth     = 340.0;
    float viewHeight    = 500.0;

    float offsetX       = viewWidth  / 2.0;
    float offsetY       = viewHeight / 2.0;

    float factorX       = viewWidth  / ( 360.0 / 6.3 );
    float factorY       = viewHeight / ( 360.0 / 6.3 );

    float angleX        = gl_FragCoord.x / factorX;
    float angleY        = gl_FragCoord.y / factorY;

    float x             = offsetX + ( sin( angleX ) * radius );
    float y             = offsetY + ( cos( angleY ) * radius );
    float c             = x + y;

    gl_FragColor = vec4( c, c, c, 1.0 );
}         

Upvotes: 1

Views: 769

Answers (1)

emackey
emackey

Reputation: 12418

Remember, this program runs separately for each individual fragment. Each one need only decide if it's in or out of the circle. No need to use sin and cos here, just measure the distance from the center of the viewport, to see if the fragment is in the circle.

Here's a disc, which is even simpler: http://glslsandbox.com/e#28997.0

uniform vec2 resolution;

void main( void ) {

    vec2 position = ( gl_FragCoord.xy / resolution.xy ) - 0.5;
    position.x *= resolution.x / resolution.y;

    float circle = 1.0 - smoothstep(0.2, 0.21, length(position));

    gl_FragColor = vec4( vec3( circle ), 1.0 );

}

And here's a circle, made by tweaking the disc a little: http://glslsandbox.com/e#28997.1

uniform vec2 resolution;

void main( void ) {

    vec2 position = ( gl_FragCoord.xy / resolution.xy ) - 0.5;
    position.x *= resolution.x / resolution.y;

    float circle = 1.0 - smoothstep(0.003, 0.005, abs(length(position) - 0.2));

    gl_FragColor = vec4( vec3( circle ), 1.0 );

}

Upvotes: 3

Related Questions