Easy 2D shader setup with quad-shader

The quad-shader JavaScript library helps you build WebGL animations easily. The library has zero dependencies and is extremely lightweight (2kB gzipped). WebGL runs on the GPU, allowing for smooth, high-frame-rate animations.

All animations on this page are generated on the fly with WebGL fragment shaders using quad-shader, Vite and TypeScript.

With fragment shaders, you have control over each pixel's color, making it perfect for Creative Coding and generating textures and patterns procedurally. With a few lines of code, you can create intricate effects.

Getting started with quad-shader

Let's take the following animation as an example:

First install quad-shader with npm install quad-shader.

After having installed the library, all it takes is (literally) three lines of JavaScript and a fairly short fragment shader, inlined as a string here for simplicity:

Assuming you have a canvas element on the page, you should see the animation. Congrats!

Passing inputs as uniforms

While the snippet above is very concise, quad-shader includes some pretty powerful features out of the box. First, the position of the current pixel is provided as vPosition. Second, the value of the uTime uniform will be continuously updated — this is done for you by quad-shader's animate() function.

By calling the uniform4f method on the object returned by animate(), we could pass a static value to set the custom uColor uniform. Though we can also register a callback which will reflect the canvas' (inherited) CSS color property at any given time — open your devtools and have some fun modifying the properties on this page! The technique used is described in this blog post.

All uniform[1234][fi] methods from WebGL are mirrored, using quad-shader's simpler API.

The uniform setters are a great way to make dynamic animations — especially if you start reacting to browser events. Try clicking this next animation!

Finally, and probably least obvious: the animation is only rendered when the canvas element is on the screen! If you scroll past it and the element exits the viewport, no frames will be rendered, saving on GPU power. As soon as the element re-enters the viewport, animation will resume, as if it had been running in the background.

For more information check out the code for this page on GitHub and give it a star if you like it!