Functional Shaders: A Colorful Intro-Part1 Solid Colors

Rupert
3 min readSep 18, 2020

--

https://www.shadertoy.com/view/Wlt3zS

Shader coding can be a daunting task but like most programming the problem can be broken down into smaller parts. For myself starting with image filters was an interesting and quickly rewarding path.

Colors in code

Colors can be represented in many ways in code(RGB, HEX/BINARY, HSL, HSV, CMYK). We will start with RGB.

RGB — is a 24-bit “color depth” constructed of three 8-bit channels of RGB data. This is three 8-bit channels, one byte for each of the R or G or B components, which is 3 bytes per pixel, 24 bit color, and up to 16.7 million color combinations (256 x 256 x 256). Add to this an 8-bit alpha channel and we have RGBA. The alpha channel is used for transparency (or opacity) of a color (i.e., the combined red, green and blue). It is used to determine how a pixel is rendered when blended with another color.

I recommend working along with this article in ShaderToy open in another tab/window. These concepts will apply in other shader platforms as well as Game Engines.

Make the screen red

ShaderToy uses floats to represent colors in a range of 0.0 to 1.0 instead of 0 to 255. An easy way to convert is to divide your color by 255. If values are less than 0 or greater than 1 the output will be the same as 0 or 1 respectively.

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
float red = 1.0;
// float red = 255.0/255.0;
float green = 0.0;
// float green = 0.0/255.0;
float blue = 0.0;

// not using alpha in this tutorial
float alpha = 1.0;
// Output to screen
fragColor = vec4(red, green, blue, alpha);
}

Replace the original code with this code. Then hold Alt and press Enter in order to run and see the result.

Practice

  • Change output to Green or Blue
  • Change to Black or White
  • Change output to Cyan, Magenta, or Yellow
  • Change to a custom color

Completed Shader

Links

In part 2 we will learn how to add an image .

In part 3 we will learn about Swizzling and Invert an image

In part 4 we will learn how to convert an image to gray scale

--

--