Convert Figma logo to code with AI

patriciogonzalezvivo logoglslCanvas

Simple tool to load GLSL shaders on HTML Canvas using WebGL

2,125
190
2,125
44

Top Related Projects

2,730

The Official Khronos WebGL Repository

106,888

JavaScript 3D Library.

5,401

👑 Functional WebGL

2,249

A node.js-style module system for GLSL! :sparkles:

WebGL lessons that start with the basics

Quick Overview

glslCanvas is a JavaScript library that simplifies the process of rendering GLSL (OpenGL Shading Language) shaders in web browsers. It provides an easy-to-use interface for creating and manipulating shader-based graphics, making it accessible for both beginners and experienced developers to work with WebGL.

Pros

  • Easy setup and integration into web projects
  • Supports both 2D and 3D shader rendering
  • Provides a simple API for interacting with shaders
  • Includes useful utilities for handling textures, uniforms, and mouse interactions

Cons

  • Limited documentation and examples compared to some larger WebGL libraries
  • May not be suitable for complex 3D rendering projects
  • Lacks built-in support for advanced features like post-processing effects
  • Performance may be lower compared to custom WebGL implementations for highly optimized scenarios

Code Examples

  1. Creating a basic glslCanvas instance:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const sandbox = new GlslCanvas(canvas);
sandbox.load(`
    #ifdef GL_ES
    precision mediump float;
    #endif

    uniform vec2 u_resolution;
    uniform float u_time;

    void main() {
        vec2 st = gl_FragCoord.xy/u_resolution.xy;
        gl_FragColor = vec4(st.x, st.y, abs(sin(u_time)), 1.0);
    }
`);
  1. Loading an image texture:
const sandbox = new GlslCanvas(canvas);
sandbox.load(`
    #ifdef GL_ES
    precision mediump float;
    #endif

    uniform vec2 u_resolution;
    uniform sampler2D u_texture;

    void main() {
        vec2 st = gl_FragCoord.xy/u_resolution.xy;
        gl_FragColor = texture2D(u_texture, st);
    }
`);
sandbox.setUniform('u_texture', 'path/to/image.jpg');
  1. Handling mouse interactions:
const sandbox = new GlslCanvas(canvas);
sandbox.load(`
    #ifdef GL_ES
    precision mediump float;
    #endif

    uniform vec2 u_resolution;
    uniform vec2 u_mouse;

    void main() {
        vec2 st = gl_FragCoord.xy/u_resolution.xy;
        vec2 mouse = u_mouse/u_resolution.xy;
        float d = distance(st, mouse);
        gl_FragColor = vec4(vec3(1.0 - d), 1.0);
    }
`);

Getting Started

  1. Include the glslCanvas library in your HTML:

    <script src="https://patriciogonzalezvivo.github.io/glslCanvas/dist/GlslCanvas.js"></script>
    
  2. Create a canvas element and initialize glslCanvas:

    const canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    const sandbox = new GlslCanvas(canvas);
    
  3. Load a shader program:

    sandbox.load(`
        // Your GLSL code here
    `);
    
  4. Optionally, set uniforms or textures:

    sandbox.setUniform('u_color', [1.0, 0.0, 0.0, 1.0]);
    sandbox.setUniform('u_texture', 'path/to/image.jpg');
    

Competitor Comparisons

2,730

The Official Khronos WebGL Repository

Pros of WebGL

  • Comprehensive and official API for web-based graphics
  • Extensive documentation and community support
  • Direct access to low-level GPU features

Cons of WebGL

  • Steeper learning curve for beginners
  • Requires more boilerplate code for basic setups
  • Less abstraction, which can lead to more complex implementations

Code Comparison

WebGL:

const gl = canvas.getContext('webgl');
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);

glslCanvas:

const canvas = new GlslCanvas('#glslCanvas');
canvas.load(fragmentShaderSource);

Summary

WebGL offers a powerful, low-level API for web graphics, providing extensive control and features. It's ideal for complex projects and performance-critical applications. However, it requires more setup and knowledge to use effectively.

glslCanvas simplifies GLSL shader usage, making it more accessible for quick prototyping and simpler projects. It abstracts away much of the WebGL boilerplate, allowing developers to focus on shader code. However, it may lack some advanced features and fine-grained control offered by raw WebGL.

The choice between these depends on project requirements, developer expertise, and desired level of control over the graphics pipeline.

106,888

JavaScript 3D Library.

Pros of three.js

  • More comprehensive 3D rendering capabilities, including complex scenes, models, and animations
  • Larger community and ecosystem, with extensive documentation and examples
  • Supports a wide range of 3D features like lighting, textures, and camera controls

Cons of three.js

  • Steeper learning curve due to its extensive feature set
  • Larger file size and potentially higher performance overhead
  • May be overkill for simple 2D or basic 3D projects

Code Comparison

three.js:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

glslCanvas:

const canvas = document.createElement('canvas');
const sandbox = new GlslCanvas(canvas);
document.body.appendChild(canvas);
sandbox.load(fragmentShader);

three.js is more suitable for complex 3D projects with extensive features, while glslCanvas is ideal for simpler shader-based visualizations and experiments. three.js offers a full-fledged 3D engine, whereas glslCanvas focuses on easy GLSL shader integration for 2D and basic 3D effects.

5,401

👑 Functional WebGL

Pros of regl

  • More flexible and powerful, allowing for complex WebGL rendering
  • Better performance for large-scale applications
  • Supports a wider range of WebGL features and techniques

Cons of regl

  • Steeper learning curve, especially for beginners
  • Requires more boilerplate code for simple tasks
  • Less suitable for quick prototyping or small projects

Code Comparison

glslCanvas:

var canvas = new GlslCanvas("#glslCanvas");
canvas.load(fragmentShader);

regl:

const regl = require('regl')();
const drawTriangle = regl({
  frag: fragmentShader,
  vert: vertexShader,
  attributes: { position: [[-1, -1], [0, 1], [1, -1]] },
  count: 3
});
drawTriangle();

Summary

glslCanvas is simpler and more beginner-friendly, ideal for quick shader experiments and small projects. regl offers more power and flexibility, suitable for larger, more complex WebGL applications. While glslCanvas focuses on fragment shaders, regl provides full control over the rendering pipeline, including vertex shaders and other WebGL features. The choice between them depends on the project's complexity and the developer's experience with WebGL.

2,249

A node.js-style module system for GLSL! :sparkles:

Pros of glslify

  • Modular approach allows for better code organization and reusability
  • Supports npm-style package management for GLSL shaders
  • Can be integrated into various build systems and workflows

Cons of glslify

  • Requires additional setup and configuration
  • May have a steeper learning curve for beginners
  • Limited to Node.js environments

Code Comparison

glslCanvas:

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform float u_time;

void main() {
    gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);
}

glslify:

#pragma glslify: noise = require('glsl-noise/simplex/3d')

varying vec3 vPosition;

void main() {
    float n = noise(vPosition * 10.0);
    gl_FragColor = vec4(vec3(n), 1.0);
}

glslCanvas is more straightforward for simple shaders, while glslify enables modular shader development with imported functions.

WebGL lessons that start with the basics

Pros of webgl-fundamentals

  • Comprehensive educational resource for WebGL
  • Covers a wide range of topics from basics to advanced techniques
  • Includes interactive examples and detailed explanations

Cons of webgl-fundamentals

  • Steeper learning curve for beginners
  • Requires more setup and boilerplate code
  • Less focused on quick shader experimentation

Code Comparison

webgl-fundamentals:

const gl = canvas.getContext("webgl");
const program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-2d", "fragment-shader-2d"]);
gl.useProgram(program);
// ... (more setup code)
gl.drawArrays(gl.TRIANGLES, 0, 3);

glslCanvas:

const canvas = new GlslCanvas("#glslCanvas");
canvas.load(`
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`);

glslCanvas provides a simpler API for quick shader experiments, while webgl-fundamentals offers a more in-depth approach to learning WebGL. The former is ideal for artists and designers focusing on fragment shaders, while the latter is better suited for developers seeking a comprehensive understanding of WebGL programming.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.

Donate

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="https://rawgit.com/patriciogonzalezvivo/glslCanvas/master/dist/GlslCanvas.js"></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:

  • data-fragment : load a fragment shader by providing the content of the shader as a string
  • data-fragment-url : load a fragment shader by providing a valid url
  • data-vertex : load a vertex shader by providing the content of the shader as a string
  • data-vertex-url : load a vertex shader by providing a valid url
  • data-textures: add a list of texture urls separated by commas (ex: data-textures="texture.jpg,normal_map.png,something.jpg"). Textures will be assigned in order to uniform sampler2D variables with names following this style: u_tex0, u_tex1, u_tex2, etc.

All the cached .glslCanvas elements will 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 case you need to reload the shader:

Reloading shaders from JS

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

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

// 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:

  • u_time: a float representing elapsed time in seconds.
  • u_resolution: a vec2 representing the dimensions of the viewport.
  • u_mouse: a vec2 representing the position of the mouse, defined in Javascript with .setMouse({x:[value],y:[value]).
  • u_tex[number]: a sampler2D containing textures loaded with the data-textures attribute.

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"
sandbox.setUniform("u_brightness",.5); 

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

// Assign a red color to "uniform vec3 u_color"
sandbox.setUniform("u_color",1,0,0); 

// Load a new texture and assign it to "uniform sampler2D u_texture"
sandbox.setUniform("u_texture","data/texture.jpg");

Quick start demo

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

Demo page: patriciogonzalezvivo.github.io/glslCanvas/

Collaborate

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

git clone https://github.com/patriciogonzalezvivo/glslCanvas.git
cd glslCanvas
yarn
  • Run rollup in dev mode while you edit
yarn run dev
  • Build for production
yarn run build
  • Push to your local fork and make your pull request

Thank you

NPM DownloadsLast 30 Days