This content got low rating by people.

Drawing Your First Circle: Understanding `distance()` in GLSL

Words
342
Reading
2 min
Listen
Play
2M

This article begins the next stage of the GLSL series, where we'll move beyond basic functions and start building procedural shapes from scratch.

If you're new to the series or would like to catch up on the fundamentals, you can find every previous lesson, along with a summary of what each tutorial covers, here:

GLSL Beginner Series: A Journey from Your First Shader to Procedural Animation

The previous series covered everything from writing your first fragment shader to working with UV coordinates, gradients, mix(), clamp(), pow(), fract(), step(), smoothstep(), animation with time, and creating procedural waves using sin() and cos().

So far in this series, we have learned how to fill the screen with color, create gradients, blend colors, repeat patterns, and animate shaders.

Most of these techniques affected the entire screen.

Now we are going to make something more interesting.

Instead of coloring every pixel the same way, we'll begin drawing actual shapes.

The first shape almost every shader programmer learns is the circle.

At first, it might seem like drawing a circle would require complicated mathematics or importing an image.

In reality, GLSL can generate a perfect circle using only a few lines of code.

The secret is a function called distance().

Once you understand how it works, you'll be able to create circles, rings, radial gradients, glowing effects, masks, ripples, and many other procedural techniques that appear throughout modern shaders.

What Is distance()?

Imagine placing a point in the middle of your screen.

Now imagine asking every single pixel the same question.

"How far away are you from this point?"

That is exactly what distance() does.

Its syntax is simple.

distance(pointA, pointB)

It compares two positions and returns the distance between them.

Pixels close to the chosen point return a small value.

Pixels farther away return a larger value.

Although this sounds simple, it opens the door to an entirely new way of creating graphics.

Instead of drawing shapes manually, every pixel decides whether it belongs inside or outside a shape based on its own distance from a point.

Drawing Your First Circle: Understanding `distance()` in GLSL | Ecency