GlslCanvas is JavaScript Library that helps you easily load GLSL Fragment and Vertex Shaders into an HTML canvas. I have used this in my Book of Shaders and glslEditor.


How to use it?

There are different ways to do this. But first, make sure you are loading the latest version of GlslCanvas.js on your page by adding this line to your HTML:

<script type="text/javascript" src=""></script>

or if you are using npm package manager on your console do:

npm install glslCanvas

The easy way

  1. Create a canvas element in your HTML.
  2. Add the class name glslCanvas to the canvas.
  3. Assign it a shader...
    • through a url using the attribute data-fragment-url
    • or directly writing your code inside the data-fragment attribute
<canvas class="glslCanvas" data-fragment-url="shader.frag" width="500" height="500"></canvas>

That's all! glslCanvas will automatically load a WebGL context in that <canvas> element, compile the shader and animate it for you.

As you can see, in this example we are loading the fragment shader by setting the attribute data-fragment-url to a url. But there are also a few other ways to load data to our glslCanvas:

All the catched .glslCanvas element whill be stored in the windows.glslCanvases array.

The JS way

Create a <canvas> element and construct a glsCanvas() sandbox from it.

var canvas = document.createElement("canvas");
var sandbox = new GlslCanvas(canvas);

In the case you need to reload the

Reloading shaders from JS

You can change the content of the shader as many times you want. Here are some examples:

// Load only the Fragment Shader
var string_frag_code = "main(){\ngl_FragColor = vec4(1.0);\n}\n";

// Load a Fragment and Vertex Shader
var string_vert_code = "attribute vec4 a_position; main(){\ggl_Position = a_position;\n}\n";
sandbox.load(string_frag_code, string_vert_code);

Default Uniforms

Some uniforms are automatically loaded for you:

You can also send your custom uniforms to a shader with .setUniform([name],[...value]). GlslCanvas will parse the value you provide to determine its type. If the value is a String, GlslCanvas will parse it as the url of a texture.

// Assign .5 to "uniform float u_brightness"

// Assign (.2,.3) to "uniform vec2 u_position"

// Assign a red color to "uniform vec3 u_color"

// Load a new texture and assign it to "uniform sampler2D u_texture"

Quick start demo

In the index.html file, you will find handy example code to start.

Demo page:


If you'd like to contribute to this code, you need to:

Thank you

Check the Git Repository