Skip to content

What Is a Shader? A Beginner's Guide to Shaders for Web Design

What is a shader? Learn how vertex and fragment shaders turn data into pixels on the GPU, what language they use, and where web designers see them.

Anand Patel tutorials
Published: Updated:
18 min read
What Is a Shader? A beginner's guide for web design, showing GLSL code producing a gradient through vertex and fragment shaders

What is a shader? It is a small program that runs on your graphics card (the GPU) and decides how a shape is positioned on screen and what color each pixel gets. If you have ever seen a smooth animated gradient, a rippling image or a glowing 3D object on a website, a shader was almost certainly doing the work. This guide is for web designers and front-end developers who keep running into the word and want a plain explanation, a tiny shader they can run, and a clear idea of when to write one and when to use one that already exists.

Table of Contents

What is a shader, in simple terms?

A shader is a short program that the GPU runs many times at once, each run handling a single vertex (a corner of a shape) or a single pixel-sized piece of the picture. You write the rule once; the GPU applies it to thousands or millions of points in parallel.

Diagram: one formula applied to every cell of a grid produces a smooth orange to navy gradient, shown next to the real demo canvas

One rule, run for every pixel, makes the whole pattern.

A spreadsheet is a good mental model. Imagine a sheet where every cell holds the same formula, and the formula can read its own row and column number. Nobody types a different value into each cell, yet the sheet fills with a pattern. A fragment shader works the same way, except the “cells” are pixels, the “row and column” are screen coordinates, and the result is a color instead of a number.

Two details explain most of the odd rules you will meet later:

  • Each run works alone. A shader instance cannot ask its neighbor what color it chose. It only knows its own inputs.
  • Everything runs at once. The GPU is built to do the same small job on huge numbers of points in parallel, which is why shaders can keep a full-screen animation smooth at 60 frames per second. A CPU, which handles a few jobs at a time, would struggle with the same work.

Vertex and fragment shaders are the two you will use for drawing on the web. Other types exist, such as compute shaders in WebGPU, which run general calculations on the GPU instead of drawing.

The word comes from early computer graphics, where small programs described how a surface reacts to light and shade. Pixar’s RenderMan, developed through the 1980s, is one of the best-known early systems built around a shading language (IEEE milestone record). Today they do far more than shading, from gradients and noise to distortion and particle effects.

What is a vertex shader?

A vertex shader is the shader that runs once for every vertex of a shape and decides where that point ends up on screen. A triangle has three vertices, so its vertex shader runs three times.

Diagram: a triangle with three vertices before and after a vertex shader moves each corner to a new position

A vertex shader moves the corners. The browser joins them into triangles.

Think of vertices as the pins on a pinboard with string stretched between them. The vertex shader moves the pins. Move them with a formula that changes over time and the shape bends, waves or spins. The browser then connects the moved pins into triangles.

In the demo later in this article, the vertex shader is one line long, because the shape is just a rectangle that covers the whole canvas. Vertex shaders get more interesting with 3D models, where moving each vertex can fake a flag blowing in the wind or a surface rippling.

What is a fragment shader?

A fragment shader is the shader that runs once for every fragment (roughly, every pixel a shape covers) and decides what color it gets. This is where gradients, textures, lighting, glow and most visible effects live.

The 480 by 270 demo canvas, a zoomed-in grid of individually colored pixels, and the numbers 129,600 fragment shader runs and 4 vertex shader runs per frame

The fragment shader colors every pixel. The canvas shown is a capture of the demo below.

Because it runs per pixel, it runs far more often than the vertex shader. The demo below draws on a 480 by 270 canvas, which is 129,600 pixels. The vertex shader runs 4 times for the rectangle; the fragment shader runs 129,600 times for every frame. At 60 frames per second that is about 7.8 million runs each second, from one small canvas.

That ratio is the reason performance advice about shaders almost always comes back to the fragment shader. Keep it small, and do work that does not vary per pixel somewhere else.

How do vertex and fragment shaders work together?

So what is a shader in practice? A vertex shader and a fragment shader, two steps of the same pipeline. The vertex shader positions the points, the browser fills in the shapes between them, and the fragment shader colors each piece. Here is the flow:

Diagram of the shader pipeline: vertices go into the vertex shader, the rasterizer turns shapes into fragments, the fragment shader colors each fragment, and the result appears as pixels on the canvas

  1. Your code supplies vertices. Positions, and optionally colors or texture coordinates, for each corner of a shape.
  2. The vertex shader moves them. It outputs the final screen position of every vertex.
  3. The rasterizer fills the shape. It works out which pixels each triangle covers and creates one fragment for each.
  4. The fragment shader colors each fragment. It outputs a color for its own pixel.
  5. The result lands on the canvas. The browser shows the finished image.

The vertex shader can pass values along to the fragment shader. WebGL calls these varyings, and the GPU smoothly blends them across the triangle. Give three corners three different colors and every pixel in between gets a blend, with no extra code.

In the browser, you reach all of this through WebGL. For how the API itself, canvas contexts and buffers fit around shaders, see What Is WebGL?.

How does JavaScript send data to a shader?

JavaScript passes data to a shader through three kinds of variables: attributes, uniforms and varyings. The demo uses the first two, and the vertex shader hands varyings on to the fragment shader.

Diagram: JavaScript sends attributes and uniforms to the vertex shader, which passes varyings to the fragment shader

Attributes, uniforms and varyings, and which stage uses them.

NameSet byChangesExample
AttributeJavaScript, from a bufferOnce per vertexThe corner positions of a shape (a_position)
UniformJavaScript, as a single valueOnce per draw callThe time or the canvas size (u_time, u_resolution)
VaryingThe vertex shaderBlended across each triangleA color passed from corner to corner

Image data, called textures, is a fourth route, and both shaders can read them. WebGL 2 uses the keywords in and out instead of attribute and varying, so check the version before you copy code. This is also how a page can make a shader react to the mouse or to scrolling: JavaScript reads the value and writes it into a uniform each frame.

What language are shaders written in?

WebGL shaders are written in GLSL ES, the OpenGL Shading Language for embedded systems. It looks like C: typed variables, functions and a main() function that the GPU calls. Different graphics systems use different languages, so the answer depends on where the shader runs:

Cards listing shader languages by platform: GLSL ES 1.00 for WebGL 1, GLSL ES 3.00 for WebGL 2, WGSL for WebGPU, HLSL for Direct3D and Metal Shading Language for Metal

The language depends on where the shader runs.

Where it runsShader languageNotes
WebGL 1 in the browserGLSL ES 1.00What the demo in this article uses
WebGL 2 in the browserGLSL ES 3.00 (#version 300 es)Newer syntax and more features
WebGPU in the browserWGSLA separate language made for WebGPU
Direct3D (Windows games)HLSLMicrosoft’s shading language
Metal (Apple platforms)Metal Shading LanguageApple’s C++-based language

As a web designer you will mostly meet GLSL, often inside a library such as Three.js, which lets you pass your own GLSL strings to a material. Check the version your library targets, because WebGL 1 and WebGL 2 shaders are not interchangeable without changes.

A small shader you can run

This page draws one rectangle that fills the canvas and lets a fragment shader color it. The color comes from two things: the pixel’s position, which blends orange into navy from left to right, and a sine wave, which adds soft horizontal bands that drift over time. Save it as an HTML file and open it in a browser with WebGL available.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Fragment shader gradient demo</title>
    <style>
      body {
        font:
          16px system-ui,
          sans-serif;
        margin: 2rem;
      }

      canvas {
        border: 1px solid #94a3b8;
        display: block;
        max-width: 100%;
      }
    </style>
  </head>
  <body>
    <h1>A gradient drawn by a fragment shader</h1>
    <canvas
      id="demo"
      width="480"
      height="270"
      role="img"
      aria-label="An orange to navy gradient with soft horizontal bands"
    ></canvas>
    <p id="status" role="status">Starting WebGL...</p>

    <script type="module">
      const canvas = document.querySelector("#demo");
      const status = document.querySelector("#status");
      const gl = canvas.getContext("webgl");

      const vertexSource = `
        attribute vec2 a_position;
        void main() {
          gl_Position = vec4(a_position, 0.0, 1.0);
        }`;

      const fragmentSource = `
        precision mediump float;
        uniform vec2 u_resolution;
        uniform float u_time;

        void main() {
          // Where am I? 0.0 to 1.0 across the canvas, in both directions.
          vec2 uv = gl_FragCoord.xy / u_resolution;

          // Blend from orange on the left to navy on the right.
          vec3 orange = vec3(0.98, 0.45, 0.15);
          vec3 navy = vec3(0.10, 0.14, 0.40);
          vec3 color = mix(orange, navy, uv.x);

          // Add soft bands that drift over time.
          float band = 0.5 + 0.5 * sin(uv.y * 12.0 + u_time * 2.0);
          color += 0.12 * band;

          gl_FragColor = vec4(color, 1.0);
        }`;

      function compile(type, source) {
        const shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
          throw new Error(gl.getShaderInfoLog(shader));
        }
        return shader;
      }

      if (!gl) {
        status.textContent = "WebGL is unavailable in this browser or device.";
      } else {
        const program = gl.createProgram();
        gl.attachShader(program, compile(gl.VERTEX_SHADER, vertexSource));
        gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fragmentSource));
        gl.linkProgram(program);
        if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
          throw new Error(gl.getProgramInfoLog(program));
        }
        gl.useProgram(program);

        // Two triangles that cover the whole canvas.
        const buffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.bufferData(
          gl.ARRAY_BUFFER,
          new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
          gl.STATIC_DRAW
        );
        const position = gl.getAttribLocation(program, "a_position");
        gl.enableVertexAttribArray(position);
        gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);

        const resolution = gl.getUniformLocation(program, "u_resolution");
        const time = gl.getUniformLocation(program, "u_time");
        gl.viewport(0, 0, canvas.width, canvas.height);

        function draw(seconds) {
          gl.uniform2f(resolution, canvas.width, canvas.height);
          gl.uniform1f(time, seconds);
          gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
        }

        // First frame at time 0, so the sampled pixels are repeatable.
        draw(0);
        const sample = (x, y) => {
          const pixel = new Uint8Array(4);
          gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
          return Array.from(pixel).join(", ");
        };
        const error = gl.getError();
        status.textContent =
          `${gl.getParameter(gl.VERSION)}; left pixel ${sample(0, 135)}; ` +
          `center pixel ${sample(240, 135)}; right pixel ${sample(479, 135)}; ` +
          (error === gl.NO_ERROR ? "no WebGL error" : `WebGL error 0x${error.toString(16)}`);

        // Then keep animating.
        const start = performance.now();
        function frame(now) {
          draw((now - start) / 1000);
          requestAnimationFrame(frame);
        }
        requestAnimationFrame(frame);
      }
    </script>
  </body>
</html>

Test result: I ran this exact page on December 4, 2026 in headless Chromium 159 (Playwright, macOS). The status line reported WebGL 1.0 (OpenGL ES 2.0), a left pixel of 255, 126, 50, 255, a center pixel of 149, 86, 81, 255, a right pixel of 37, 47, 113, 255, and no WebGL error. The pixels are sampled from the first frame at time 0, so they are repeatable. Other browsers and devices can differ slightly.

Screenshot of the shader demo in Chromium: an orange to navy gradient with soft horizontal bands, and a status line showing the sampled pixels and no WebGL error

Screenshot of the demo in Chromium; the bands drift, so a frame you capture will look slightly different.

The fragment shader is the part to read closely:

  • precision mediump float; is required in a WebGL 1 fragment shader. It sets the default precision for decimal numbers.
  • gl_FragCoord.xy / u_resolution turns the pixel’s position into a number from 0 to 1 in each direction. That is the “row and column” from the spreadsheet comparison.
  • mix(orange, navy, uv.x) blends two colors. At the left edge (uv.x near 0) you get orange, at the right edge you get navy.
  • sin(uv.y * 12.0 + u_time * 2.0) makes a wave that depends on the pixel’s height and on time. The u_time value is a uniform: a number your JavaScript sets once per frame that every pixel can read.

One mistake to watch for: delete the precision mediump float; line and the shader stops compiling. In my test run (headless Chromium 159), the console reported No precision specified for (float) once for every line that used a decimal number. Put the line back and the page works again.

Change 12.0 to 30.0 for thinner bands, or swap the two vec3 colors for your brand colors, and reload. Small edits like these are the quickest way to build a feel for shader math.

Skip the GLSL: If you want a finished shader effect instead of writing one, browse the MotionUIKit shader components, pick one and copy it into your project.

Where do shaders show up in web design?

Shaders are behind most effects on the web that feel smooth, soft or physical and that CSS alone cannot do. Common uses include:

Four examples of shader uses: animated gradients and noise, image distortion, particles and glow, and 3D scenes

Common places shaders appear on the web.

  • Animated gradients and noise. Color that flows, shifts or grains in ways a CSS gradient cannot.
  • Image effects. Ripples, distortion on hover, color splitting and transitions between images.
  • Particles and glow. Thousands of moving points or soft light, drawn in one pass instead of thousands of DOM elements.
  • 3D scenes. Product viewers, interactive heroes and scroll-driven 3D, where shaders handle lighting and materials.

CSS and SVG are still the better tools for ordinary layout, simple gradients and small transitions. Reach for a shader when the effect depends on per-pixel math, runs on a large area, or has to stay smooth with a lot happening at once.

Should you write your own shader or use a ready-made one?

Write your own when you need a look nobody ships, or when learning shaders is itself the goal. Use a ready-made one when you need a polished effect on a deadline. Here is how the trade-off looks:

Write your ownAdapt a ready-made one
Time to a working result (rough estimate)Often hours to daysOften minutes
Control over the lookCompleteWhatever its settings allow
Skills neededGLSL, coordinates, debugging on the GPUBasic JavaScript or a copy-paste
RiskShader bugs are hard to debug, and a heavy one can slow the pageCheck what it costs on slow devices

Most websites need the second column. My rule of thumb: before you write a shader from scratch, change three numbers in someone else’s shader and see if you can predict what each one does. If you can, you are ready to write your own. Learning the basics from this article still helps, because you will read and tweak ready-made shaders far more confidently when you know which part is the vertex shader, which is the fragment shader and what a uniform is.

How to add a shader effect to your website

You do not have to write GLSL to get a shader effect on a real page. This is the quickest route:

  1. Open a library of ready-made effects. Look for full-page sections or single shader components, and preview the options.
  2. Pick one that fits the page. Match it to the job, for example a hero for a landing page or an effect for a feature block.
  3. Add it to your project. Copy the code, or use the CLI command or AI prompt shown on the section’s page. Follow the install steps listed there, because they can differ from section to section.
  4. Change the content and colors. Replace the headline, copy and assets, then adjust the colors to match your brand.
  5. Plan for no WebGL and for reduced motion. Keep a static image or plain CSS version for visitors whose canvas.getContext("webgl") returns null, and pause or simplify the animation for people who have asked for reduced motion with the prefers-reduced-motion media query.

Do shaders slow down a website?

They can, but a small shader on one canvas is usually fine. The cost comes from how many pixels the fragment shader has to color and how much work it does for each.

Bar chart comparing 129,600 fragment shader runs per frame on the demo canvas with 2,073,600 on a 1920 by 1080 canvas, 16 times more

More pixels means more fragment shader runs every frame.

The demo above colors 129,600 pixels per frame. A full-screen canvas on a large display is many times that, and on a phone with a device pixel ratio of 2 the same area needs four times as many pixels as its CSS size suggests. The cost multiplies with the amount of math in each run.

To keep a shader cheap:

  • Keep the fragment shader short, and avoid loops that run for every pixel.
  • Render the canvas at a lower resolution than the screen when the effect is soft anyway.
  • Pause the animation when the canvas is off screen or the tab is hidden.
  • Test on a modest phone, not just your development machine.
  • Handle the webglcontextlost event and provide a fallback, as described in MDN’s WebGL best-practices guide.

Measure before you guess. Browser developer tools show frame times, and a page that holds a steady 60 frames per second on the weakest device you care about is fine.

Common questions

Is a shader the same as a texture or a material?

No. A texture is image data, such as a photo or a pattern. A material is a bundle of settings that describes how a surface looks. A shader is the program that uses them to work out the final color. Libraries such as Three.js often hide the shader behind a material, which is why you can use 3D graphics without ever seeing one.

Are shaders only for 3D?

No. The demo in this article draws a flat gradient and uses no 3D at all. Shaders color pixels, and a pixel does not care whether it belongs to a 3D model or a flat rectangle. Many popular web effects are 2D shaders.

Can I use shaders without knowing GLSL?

Yes. You can use a library’s built-in materials, a ready-made section or effect, or a visual tool, and change only the settings it exposes. Learning GLSL pays off when you want to change what an effect does rather than how it is tuned. Free resources such as The Book of Shaders and Shadertoy are good places to practise once you are ready.

Can a shader read my page’s HTML or CSS?

No. A shader runs on the GPU, outside the page, and cannot read the DOM, your CSS or any other web API. It only sees the numbers and textures that JavaScript passes in. To make a shader respond to something on the page, such as the mouse position or scroll offset, read that value in JavaScript and send it through a uniform.

What is a shader in CSS?

There is no shader in CSS itself. You cannot write a vertex or fragment shader in a stylesheet. Browsers may use the GPU to draw CSS effects such as filters and transforms, but the shaders behind that are internal. For a custom per-pixel effect, draw to a canvas with WebGL, as in the demo above.

What is a shader in Three.js?

In Three.js, a shader is the GLSL code you attach to a material when the built-in materials are not enough. The library’s ShaderMaterial class takes a vertex shader and a fragment shader as strings, and Three.js handles the canvas, buffers and drawing around them.

What is a shader in WebGL?

In WebGL, a shader is the small program you hand to the GPU, and WebGL is the browser API that carries it there. WebGL sets up the canvas, buffers and drawing commands; the shaders decide the positions and colors. What Is WebGL? covers the API side.

What is a shader used for?

A shader is used to position shapes and color pixels on the GPU. On websites that means animated gradients, image distortion, particle effects and 3D scenes. The section Where do shaders show up in web design? lists examples.

You may also like

MotionUIKit

Build landing pages that move

Animated sections, templates and components for React and HTML. Copy the code, use the CLI or paste an AI prompt, and ship a site that feels alive.