Articles Article

Shaders, and how to let your editors tune them

What a shader is, where you've already seen them on blutui.com and how to build Canopy Blocks that let editors change a shader's colours and motion.

Product 10 min read

Shaders, and how to let your editors tune them

The top of every page on blutui.com moves. Sit on the home page for a few seconds and you'll see it: a dark blue pattern of tiny dots drifting behind the headline. It's a shader, a short program that the graphics card in your laptop or phone runs on every frame, with no video or image file to download.

We use shaders in a few places on the site, and we've built Canopy Blocks that let an editor change a shader's colours and motion without opening the code. The code for those blocks is on GitHub so you can use it in your own Blutui project.

What a shader is

A screen is a grid of pixels, and something has to work out the colour of each one, sixty or more times a second. A CPU has a handful of cores that are good at long, complicated jobs. A GPU has thousands of small ones that are good at doing the same simple job many times at once. A shader is the small program you hand the GPU for that job.

The kind this post is about is a fragment shader, sometimes called a pixel shader. The GPU asks it the same question for every pixel: here's where you are and here's the time, what colour are you? It answers with four numbers between 0 and 1 for red, green, blue and alpha. Every pixel gets its answer in parallel, and then the whole thing runs again for the next frame.

This is a complete one:

precision mediump float;
uniform vec2 u_resolution;
uniform float u_time;

void main() {
  vec2 uv = gl_FragCoord.xy / u_resolution;   // 0,0 bottom left to 1,1 top right
  vec3 colour = 0.5 + 0.5 * cos(u_time + uv.xyx + vec3(0.0, 2.0, 4.0));
  gl_FragColor = vec4(colour, 1.0);
}

uv is where the pixel sits on the canvas. The cos() line turns that position and the time into a colour, and as the time moves on the colours shift with it.

u_resolution and u_time are uniforms. A uniform is a value you set from JavaScript before a frame is drawn, and every pixel sees the same value. They're the only way to get information into a shader from the outside, and they're what the rest of this post is about: making a shader editable comes down to turning an editor's settings into uniforms.

Shaders are written in GLSL, which looks a lot like C, and on the web WebGL is what hands them to the GPU. The example above with all its plumbing (a canvas, one rectangle to draw on and the two uniforms updated each frame) is hello-shader.html in the repo.

Where you've already seen them

Games have used shaders for decades for water, fire, shadows and reflections. Most of what you'd call an effect on a screen is one too: the filters in your phone's camera app, the frosted blur behind a menu and the animated gradients that look like coloured liquid at the top of so many product sites.

Our own site runs two, in five places.

The dither at the top of every page

This is the dithering shader from Paper Shaders, drawn in two navy colours (#000B5A and #142384) with a 4×4 dither pattern and a warp that moves at about a fifth of normal speed. It runs twice as tall on the home page as everywhere else.

The blutui.com home page with its dithered shader
The same page with the shader hidden: flat navy
The home page with its shader, and without it.

The gradient under the header

On platform and solution pages a gradient band starts under the heading. We wrote this one ourselves. It's a WebGL version of the mesh gradient fill in our Figma designs: a 4×4 grid of colour points blended into each other, with a slow warp on top that's kept gentle enough that the sheet never folds over itself. The Content Gradient block has a Colour setting with five palettes, so Build and Manage can run the same gradient in different colours. On our own site, then, an editor could already pick a shader's colours from a dropdown before this demo existed.

The Build page with its shaders
The Build page with its shaders hidden
Build with and without its shaders.

The closing section and the footer

The closing section on solution pages sits on the same gradient, and the site footer runs it upside down so its densest colour is at the bottom of the page.

The share cards

When you paste a blutui.com link into Slack or LinkedIn, the preview image is drawn by the same dither and gradient code that the page runs, so the card looks like the page it came from.

The share card for the Build page
The share card for the Build page, drawn with the page's own shaders.

Turn them all off and the site still works, just flatter. Each one is drawn over a background colour that's already right, and a browser that can't run the shader shows that colour instead.

What they cost

Shaders aren't free, and we found that out from a PageSpeed Insights report: 21 seconds of blocking time on the home page. PageSpeed's copy of Chrome has no GPU, so it draws WebGL in software on the CPU, and every frame of the dither became a long task on the main thread. A Lighthouse run on a laptop showed the same thing at 11 seconds.

The fix is to check before mounting anything. We ask for a WebGL context that the browser refuses to create if it would be slow, then read the renderer's name. If it's a software renderer, the shader is skipped and the page keeps its flat colour.

export function hasGpuWebGL() {
  const gl = document.createElement('canvas').getContext('webgl', { failIfMajorPerformanceCaveat: true });
  if (!gl) return false;
  const info = gl.getExtension('WEBGL_debug_renderer_info');
  const renderer = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) || '');
  gl.getExtension('WEBGL_lose_context')?.loseContext();
  return !/swiftshader|llvmpipe|softpipe|software|basic render/i.test(renderer);
}

The renderer name is there because the first check misses SwiftShader when it's turned on with a command-line flag, which is how PageSpeed gets WebGL.

The dither holds still in the Canopy editor, so nothing moves while someone edits the page, and for anyone who has asked their system for reduced motion. Paper Shaders already pauses a shader when it scrolls out of view or the tab is in the background.

Letting editors tune a shader in Blutui

The palette picker on Content Gradient was a start. For this post we built a small demo project that goes further: three blocks, each wrapping a shader from Paper Shaders, with every colour and slider an editor might want on a Shader tab in Canopy.

Every setting takes the same route:

block setting → data-* attribute → JavaScript reads it → uniform → GPU

Diagram: a Colour setting of #f75092 becomes a data-colors attribute, then the third colour in the u_colors uniform, then pixels on the GPU

Each block's template prints its settings into HTML attributes. One JavaScript file, written once, reads those attributes and turns them into uniforms. Editors never see code, and a new block only needs new JavaScript if it uses a shader the runtime doesn't know yet.

1. Give the block its settings

Settings go in the block's {% canopy config %}, and the setting type depends on the kind of shader option:

Shader optionSetting typeWhy
ColourscolorGives a hex string such as #f75092
Strengths between 0 and 1 (distortion, softness, noise)number, 0 to 100Editors think in percentages, so the JavaScript divides by 100
A fixed list (shape, dither type)select or radioNobody can type a value the shader doesn't accept
On or off (pause)checkboxA plain yes or no

Tabs and groups keep the Shader settings away from the Content ones:

{ "name": "color_1", "type": "color", "label": "Colour 1", "tab": "Shader", "group": "Colours", "default": "#e0eaff" },
{ "name": "distortion", "type": "number", "tab": "Shader", "group": "Shape", "min": 0, "max": 100, "default": 80, "help": "Organic noise distortion (0–100)" },
{ "name": "shape", "type": "select", "tab": "Shader", "group": "Pattern", "default": "corners", "options": [{ "value": "wave", "label": "Wave" }, { "value": "corners", "label": "Corners" }] },
{ "name": "paused", "type": "checkbox", "label": "Pause animation", "tab": "Shader", "group": "Motion", "default": false }

Give every setting a default, so the block looks finished the moment an editor adds it.

The Canopy editor with the Mesh Gradient Hero selected and its Shader tab open
The hero's Shader tab in Canopy: four colours, then the Shape and Motion groups.

2. Print the settings as data attributes

The shader mounts into an empty div behind the content, and every setting becomes one attribute on it:

<section class="relative isolate overflow-hidden" style="background-color: {{ settings.color_2 }}">
  <div
    class="absolute inset-0 -z-10"
    aria-hidden="true"
    data-shader="mesh-gradient"
    data-colors="{{ [settings.color_1, settings.color_2, settings.color_3, settings.color_4]|join(',') }}"
    data-distortion="{{ settings.distortion }}"
    data-swirl="{{ settings.swirl }}"
    data-speed="{{ settings.speed }}"
    data-paused="{{ settings.paused ? 'true' : 'false' }}"
  ></div>
  ...
</section>

data-shader says which shader to run. The four colour settings are joined into one attribute with |join(',') and split again in JavaScript. The checkbox is printed as 'true' or 'false', because an attribute's value is always a string. The section's background-color is one of the shader's own colours, so the block still looks intended where WebGL isn't available, and aria-hidden tells screen readers the canvas is decoration.

3. Load the runtime from the block

{% canopy scripts %}
{{ asset('js/shaders.js') | script_tag }}
{% endcanopy %}

Blutui only outputs this on pages that use one of the blocks. The layout calls canopy.scripts('main') with the same area handle as canopy.blocks('main'). All three blocks include the same file, so the runtime checks a flag on window and only starts once.

4. Turn attributes into uniforms

src/js/shaders.js keeps a registry with one entry per value of data-shader. Each entry has the shader's GLSL and a function that maps the element's dataset to uniforms:

const SHADERS = {
  'mesh-gradient': {
    fragment: meshGradientFragmentShader,
    uniforms: (data) => {
      const colors = colorList(data.colors);        // "#e0eaff,#241d9a,…" → [[r,g,b,a], …]
      return {
        ...sizing(data),                            // fit, scale, rotation
        u_colors: colors,
        u_colorsCount: colors.length,
        u_distortion: percent(data.distortion, 0.8), // "80" → 0.8
        u_swirl: percent(data.swirl, 0.1),
        u_grainMixer: 0,
        u_grainOverlay: percent(data.grain, 0),
      };
    },
  },
};

new ShaderMount(el, def.fragment, def.uniforms(el.dataset), undefined, speed);

getShaderColorFromString() from Paper turns a hex string into the four 0 to 1 numbers a shader uses. percent() turns an editor's 80 into 0.8. Lookup tables that ship with Paper (GrainGradientShapes, DitheringShapes, DitheringTypes) turn a select value such as "ripple" into the number the shader expects.

One naming detail is easy to miss: data-color-back arrives in JavaScript as dataset.colorBack. Kebab case in the HTML, camel case in the script.

5. Keep it live in the editor

When an editor changes a setting, Canopy re-renders the block. A MutationObserver in the runtime watches for that. A new [data-shader] element gets a shader mounted. An element that has left the page gets dispose(), which frees its WebGL context, and browsers cap how many of those a page can have. When only an attribute has changed, setUniforms() and setSpeed() update the running shader without mounting it again.

Changing Colour 3, Distortion and Rotation in Canopy, with the preview updating as each value is typed
Colour 3, Distortion and Rotation changed in the editor. The shader updates as each value is typed, before anything is applied.

Speed runs from 0 to 200, with 100 as normal. The Pause checkbox sets it to 0, and so does a reader's reduced motion setting. At 0 the render loop stops, so a paused shader costs nothing.

The three demo blocks, each with its default settings and two others: the mesh gradient in pink, sunset and mint; the grain gradient in corners, ripple and blob; the dither as a blue sphere, a citron warp and red ripples
Each row is one block. Only its Shader settings changed.

Things that caught us out

  • The block config has to be strict JSON. A stray comma hides the field in the editor without any error.

  • Uniform names have to match the shader's exactly. A misspelt one is ignored, also without an error. Each shader's .d.ts file in node_modules/@paper-design/shaders/dist/shaders/ lists the ones it takes.

  • setUniforms() only updates uniforms that were set when the shader mounted, so uniforms() should always return the full set.

  • The grain gradient needs a noise texture, and the image has to finish loading before the shader mounts. It's the one input in the demo that isn't an editor setting.

  • The mesh gradient takes up to 10 colours and the grain gradient up to 7. u_colorsCount has to match the length of the array.

  • Three or four shader blocks on a page is fine. Dozens would run into the browser's limit on WebGL contexts.

  • The runtime is built by Parcel from src/js/shaders.js. Edit that, run npm run build, then courier push. Courier only syncs views/ and public/.

Adding a setting of your own

Say you want a Swirl slider on the grain block:

  1. Add it to the config: { "name": "swirl", "type": "number", "tab": "Shader", "min": 0, "max": 100, "default": 0 }

  2. Print it in the template: data-swirl="{{ settings.swirl }}"

  3. Map it in the registry: u_swirl: percent(data.swirl, 0) in that shader's uniforms(), after checking its .d.ts that the shader takes u_swirl.

  4. Add data-swirl to the observer's attributeFilter so the editor updates it live.

  5. npm run build, then courier push.

A whole new shader is much the same: import its fragment shader from @paper-design/shaders, add an entry to SHADERS, make a block with a div whose data-shader names it and add the block to the area's list in the layout.

Try it

The demo project is at github.com/blutui/shaders. Clone it, run npm install and npm run build, point courier.json at your own project and run courier push. Then open the home page in Canopy and go to any block's Shader tab. Every shader in it comes from Paper Shaders, which is also where to look for the next one to wrap.