An Introduction to Shaders - Frontend Horse
Tags: webdev, html, css, javascript
Published: 2020-07-26 18:13:51

_This is an issue from the newsletter Frontend Horse. This was originally published on July 16th, 2020. Visit [Frontend.Horse](https://frontend.horse) to subscribe and find more issues._

---


Howdy, and welcome to the thoroughbred web-dev newsletter!

We've got something extra special on the trail this week. In collaboration with the amazing [ilithya](https://www.ilithya.rocks), we're bringing you an introduction to **shaders**!

Shaders can be a super power for a frontend developer, so it's good to have a general understanding of what they are and how they work. That's what this issue is all about.

It's an overview of some main shader concepts and will serve as a gentle introduction to the wide world of shaders. If you already have some shader experience, this might help you solidify some of your understanding as well.

In a future issue we'll dive into the awesome shaders [ilithya makes on CodePen](https://codepen.io/ilithya), so keep an eye out for that.

Let's hit the trail and learn about **shaders**!

---

## A Conceptual Shader Introduction

Shaders can feel a bit overwhelming if we immediately jump into the code. Instead, let's gain a high-level understanding of shaders by using a metaphor.

#### A Pixel Classroom

Let's imagine a classroom of pixel students. Real screens can hold thousands of pixels, but for simplicity,  there are just 16 pixels in this classroom representing our screen. The students' desks are lined up in 4 rows and 4 columns.

![A grid of pixels 4 x 4](https://dev-to-uploads.s3.amazonaws.com/i/kqggu615s6vqfl6esezz.png)

Each pixel is taking a shader test **to determine its color**. Like any good school, there's **no cheating!** Each pixel has **the same test** and has to complete it **on their own**. Everyone takes the test at the same time and changes color to the answer at the same time.

So if we want to make a solid pink shader, we'd give everyone a test that returns the color pink.

![The grid of pixels turning pink](https://dev-to-uploads.s3.amazonaws.com/i/dlspxk5kw2z874j440bi.png)

Each student gets the same answer because there are no dynamic values. It's all hard-coded.

So how would we make a gradient?

We can't hard-code the gradient by handing students slightly different tests. **Remember: each student gets the same test.**

However, our pixel students know where they sit in the classroom, and we can reference their column and row numbers on the test. If the test tells them to set their **opacity** of the pink color equal to 3 divided by their column number, the students across the columns will get:

 `0`,

 `0.33`,

 `0.66`,

 and  `1.0`.

With that set to their opacity our classroom will go from white to pink like this:

![pixels-3.png](https://dev-to-uploads.s3.amazonaws.com/i/d8xsdx1pmvvos1rmce2d.png)

This little pixel classroom is heavily simplified but helps us grasp some basic shader principles. Shader artists use factors like pixel position, the time, and math like sine waves and random values to create amazing visuals.

It's important to note that shaders are great for animations. Our pixels are super fast and can take 60 tests every second (60 frames per second), as long as they're not too complex.

Now that we have a metaphor to work with, let's transition to reality and learn what shaders are.

#### So what is a shader?

Shaders are a special program that run on your computer's Graphics Processing Unit (GPU) instead of the CPU. The shader program gets called for each individual pixel in parallel, making them super fast. This was our classroom all taking the test at the same time.

This comes with a catch, though: you need to design shaders differently than you might a JavaScript function.

If I wanted to color a grid of pixels with JavaScript I might write a loop like this.

```JavaScript
// Loop across each pixel and change one at a time
for (let i = 0; i < width; i++) {
  for (let j = 0; j < height; j++) {
    grid[i][j] = someColor;
  }
}
```

But this changes one pixel at a time in the order of the loops. This would be like our students being told by the teacher one at a time what color they should show.

With shaders you only have access to the inside of the loop, so you’d write this.

```GLSL
// function called for every pixel at the same time
void main() {
  COLOR = some_color;
}
```

Shaders are incredibly versatile and are used in graphics across movies, video games, and the web! That animated gradient on [the new Stripe site](https://www.stripe.com/)? That’s a shader!

#### Vertex and Fragment Shaders

There are two types of shaders, **vertex shaders** and **fragment shaders**. While we're only talking about fragment shaders today, It's helpful to briefly touch on the difference. Vertex shaders change the **vertices of a shape**, while fragment shaders change the **pixels inside that shape**.

A vertex shader defines the **shape** of our pixel classroom while the fragment shader controls the **color of the pixels** inside.

![verts-pixels.png](https://dev-to-uploads.s3.amazonaws.com/i/q2fmus50r9douh7w4d60.png)

We need both to make our image, but our vertex shader is very simple when we want to focus on the colors.

Cool, so I'm beginning to understand what shaders are, and I know they’re awesome. How tough is it to become a shader expert?

#### Are shaders hard?

Ilithya explained that getting started with shaders can be tough. They’re **not written in JavaScript**, but in OpenGL Shading Language (**GLSL**), a C-style language. She also said that yeah, you should be decent with math if you’re going to be making *custom* shaders.

But ilithya told me how to start learning shaders *without* getting a mathematics degree or learning C:

**Tweak other people’s shaders.**

For any piece of code you’re trying to figure out: **try to break it**. Learn what each line does through trial and error. Then add comments as you figure it out.

Use a simple shader example as a starting point. Find the numbers in the shader and change them to see what they do. This playing with values, and changing a `+` to a `-` to see what happens is exactly how ilithya got started.

Now we've covered a conceptual overview of shaders. Let's take a look at a few shaders to see some of what's possible.

## Shader Examples

Here are just a few examples of shaders used on the web. I recommend searching on CodePen and other similar sites for 'shader' to see what's out there.

![grunge-poster.png](https://dev-to-uploads.s3.amazonaws.com/i/rcz6w2jqypqsmhsmec61.png)

[ilithya](https://codepen.io/ilithya/full/MWwxEvp)

![mav-farm.png](https://dev-to-uploads.s3.amazonaws.com/i/q0ymx7e748kp1sk726i0.png)

[Mav Farm](https://mav.farm/)

![halftone-circles.png](https://dev-to-uploads.s3.amazonaws.com/i/w5k2ulxsgu4467569yty.png)

[Lea Rosema](https://codepen.io/terabaud/pen/BajJbgd)

![psychadelic-waves.png](https://dev-to-uploads.s3.amazonaws.com/i/z2z2q582ylvpavq7tlpf.png)

[Karim Maaloul](https://codepen.io/Yakudoo/pen/rJjOJx)

## Shader Resources

#### The Book of Shaders

Ilithya pointed us to the holy grail of shader resources: [The Book of Shaders](https://thebookofshaders.com/). The authors take you by the hand and show you how a few basic shaders work. Like giving you red and yellow paint, then you mix them yourself to discover orange.

The site has tons of working code demos, and they even point out lines of code that you should edit to change the effect. They even have a super helpful [introduction for those coming from JS](https://thebookofshaders.com/appendix/04/).

#### ShaderToy

[ShaderToy](https://www.shadertoy.com/) is basically a CodePen dedicated purely to shaders. There’s some incredible stuff here, so don’t get overwhelmed. Start with the Book of Shaders to learn the basics, but peek here to see what’s possible.

Check out [ilithya’s site](https://www.ilithya.rocks/) and [her CodePen ->](https://codepen.io/ilithya)

---

## So Long, Partner

Well, that’s the end of the trail for this week. I appreciate you riding with me.

Follow **[@FrontendHorse on Twitter](https://twitter.com/frontendhorse)**, and if you enjoyed this, I’d be over the moon if you share it with a friend or tweet about it.

Extra special thanks to ilithya for helping me write this piece for **two weeks!** It went through a ton of revisions and she provided so much information and feedback for both parts of the issue. Please assume that any mistakes are mine and anything clever was her insight. It was a huge collaborative effort and I'm incredibly thankful!

This issue was very different from previous issues, so I'd love to know what you think. You can reply to this email to let me know. I read everything I get.

This is the part where we ride off into the sunset. You take care.

Your Neigh-bor,

Alex


---

If you liked this post, head to [Frontend.Horse](https://www.frontend.horse) to subscribe! You'll get the next issue before it's posted here on Dev.