Simon Willison’s Weblog

Subscribe

Animating Rick and Morty One Pixel at a Time (via) Daniel Hooper says he spent 8 months working on the post, the culmination of which is an animation of Rick from Rick and Morty, implemented in 240 lines of GLSL - the OpenGL Shading Language which apparently has been directly supported by browsers for many years.

The result is a comprehensive GLSL tutorial, complete with interactive examples of each of the steps used to generate the final animation which you can tinker with directly on the page. It feels a bit like Logo!

Animated demo - as I edit the shader code Rick's half-drawn eye pupils move from side to side live with my edits

Shaders work by running code for each pixel to return that pixel's color - in this case the color_for_pixel() function is wired up as the core logic of the shader.

Here's Daniel's code for the live shader editor he built for this post. It looks like this is the function that does the most important work:

function loadShader(shaderSource, shaderType) {
    const shader = gl.createShader(shaderType);
    gl.shaderSource(shader, shaderSource);
    gl.compileShader(shader);
    const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (!compiled) {
        const lastError = gl.getShaderInfoLog(shader);
        gl.deleteShader(shader);
        return lastError;
    }
    return shader;
}

Where gl is a canvas.getContext("webgl2") WebGL2RenderingContext object, described by MDN here.