Black and White

Functional Shaders: A Colorful Intro-Part6 — Black & White

Rupert
2 min readSep 28, 2020

--

Black & White shader is a simple continuation of the grayscale shader tutorial.

Missed Part1?

https://medium.com/@rupertontheloose/functional-shaders-a-colorful-intro-b774affe69ad

Convert to Gray Scale or Luma

// get gray scale or luminescence
float gray = 0.33 * (color.r + color.g + color.b);

Use a threshold to decide if the fragment/pixel will be white or black

// mix white and black by the value of step(threshold, gray)
float threshold = 0.5;
if(gray > threshold)
{
// white
color.rgb = vec3(1.0);
}
else
{
// black
color.rgb = vec3(0.0);
}

Another way using Mix Function instead of if statements

The mix function performs a linear interpolation between x and y using a to weight between them. If a = 0.0 then returns x, if a = 1.0 then returns y.

mix(x, y, a)

vec3 BlackAndWhiteThreshold(vec3 color, float threshold)
{
float luma = 0.333333 * (color.r + color.g + color.b);
float l= mix(0.0, 1.0, step(threshold, luma));
return vec3(l);
}
// Another way
color = texture(iChannel0, uv);
color.rgb = BlackAndWhiteThreshold(texColor.rgb, 0.5);

Completed Shader

More on Gray Scale

--

--