Shaders


About this project


A couple of years ago I became very interestd in learning about Shaders. I started reading The Book of Shaders, which also includes a live canvas to test the code that you're learning about.

So, as an exercise, I wanted to recreate such a canvas for this website as well.

Technical details


As it turns out, there already exists a library called glslCanvas that does exactly that.

Now I just needed to have a code editor and a way to update the shaders from it. I decided to use CodeMirror as it fits the bill perfectly.

The setup was the unfortunately quite troublesome, but I managed to get it done in the end. I'm using the One Dark theme for this Website, which is objectively the best :).

To update the canvas, I needed to set the data-fragment tag of the canvas to the shader code. This was done in the following JS:

JavaScript
// Setting up the editor
new EditorView({
     doc: document.querySelector("#shader-canvas").getAttribute("data-fragment"),
     extensions: [
         basicSetup,
         StreamingLanguage.define(shader),
         oneDarkTheme,
         fixedHeightEditor,
         darkHighlightExtension,
         // The event listener:
         EditorView.updateListener.of(docUpdate => updateShaderCanvas(docUpdate))],
     parent: document.querySelector("#shader-editor"),
});

Of course, we also need the updateShaderCanvas function, which is quite simple:

JavaScript
const updateShaderCanvas = (docUpdate) => {
     if (docUpdate.docChanged) {
         let raw_text = "";
         if (docUpdate.state.doc.text != undefined) {
             docUpdate.state.doc.text.forEarch((line) => { raw_text += line + "\n"; });
         }
         else {
             docUpdate.state.doc.children.forEarch((child) => { raw_text += child.text.join("\n"); });
         }
         let sandbox = new GlslCanvas(shader_canvas);
         sandbox.load(raw_text)
     }
}