Shaders in GLSL Canvas

Table of Contents

Categories: #graphics 

GLSL Library

GLSL Canvas is a library that allows you to run GLSL shaders in a web environment. It makes it easy to create interactive graphics and visualizations using shader language inside a canvas element with WebGL.

https://github.com/patriciogonzalezvivo/glslCanvas

1<script type="text/javascript" src="https://rawgit.com/patriciogonzalezvivo/glslCanvas/master/dist/GlslCanvas.js"></script>

ShaderToy -> GLSL Canvas

The original shader we’ll be using was written for ShaderToy, which uses a specific set of uniforms and functions. In GLSL Canvas, we need to adapt the code to use the u_time and u_resolution uniforms provided by the library. The main function will also be adjusted to fit the GLSL Canvas structure.

 1#define iTime u_time
 2#define iResolution vec3(u_resolution, 1.0)
 3uniform float u_time;
 4uniform vec2 u_resolution;
 5
 6//Shadertoy fragment shader main function
 7void mainImage( out vec4 fragColor, in vec2 fragCoord );
 8
 9//GLSL Canvas main function
10void main() {
11    vec4 color = vec4(0.0);
12    mainImage(color, gl_FragCoord.xy);
13    gl_FragColor = color;
14}

HTML Setup

To use GLSL Canvas, you need to include the library in your HTML file and create a canvas element where the shader will be rendered. Here’s a simple setup:

 1<script type="text/javascript" src="https://rawgit.com/patriciogonzalezvivo/glslCanvas/master/dist/GlslCanvas.js"></script>
 2
 3<textarea id="shaderEditor">
 4    {{ GLSL shader code here }}
 5</textarea>
 6
 7<canvas id="shaderCanvas" style="display:block; width:100%; height:500px;"></canvas>
 8
 9<script>
10const canvas = document.getElementById("shaderCanvas");
11const sandbox = new GlslCanvas(canvas);
12const editor = document.getElementById("shaderEditor");
13
14function resizeCanvasToCSSSize() {
15    const displayWidth = canvas.clientWidth;
16    const displayHeight = canvas.clientHeight;
17
18    // Only update if size changed
19    if (canvas.width !== displayWidth || canvas.height !== displayHeight) {
20      canvas.width = displayWidth;
21      canvas.height = displayHeight;
22    }
23  }
24
25// Resize initially and on window resize
26resizeCanvasToCSSSize();
27sandbox.load(editor.value);
28editor.addEventListener("input", () => {
29    sandbox.load(editor.value);
30});
31</script>

Shader: Spiral

You can edit the values in the textarea below to see how they affect the shader in real-time. The shader creates a colorful spiral effect that changes over time.

I recomend focusing on the width, dis, blur, rep, mul, and ex variables to see how they affect the spiral’s appearance.

The points variable controls the number of points in the spiral.

Original Shader

https://www.shadertoy.com/view/Wct3zX