Convert Figma logo to code with AI

oframe logoogl

Minimal WebGL Library

3,696
209
3,696
19

Top Related Projects

101,622

JavaScript 3D Library.

43,513

The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.

5,213

👑 Functional WebGL

A lightweight 3D physics engine written in JavaScript.

🇨🇭 A React renderer for Three.js

Babylon.js is a powerful, beautiful, simple, and open game and rendering engine packed into a friendly JavaScript framework.

Quick Overview

OGL (O-GL) is a minimal WebGL framework designed for high-performance 3D graphics applications. It provides a lightweight and efficient solution for creating 3D scenes, geometries, and shaders in the browser, focusing on modern JavaScript practices and optimal performance.

Pros

  • Lightweight and minimalistic, resulting in fast performance
  • Modern JavaScript syntax and modular structure
  • Flexible and customizable, allowing for low-level control
  • Well-documented with examples and tutorials

Cons

  • Less feature-rich compared to larger 3D libraries like Three.js
  • Steeper learning curve for beginners due to its low-level nature
  • Limited community support compared to more popular alternatives
  • Fewer ready-made components and effects

Code Examples

Creating a basic scene with a rotating cube:

import { Renderer, Camera, Transform, Box, Program, Mesh } from 'ogl';

const renderer = new Renderer();
const gl = renderer.gl;
document.body.appendChild(gl.canvas);

const camera = new Camera(gl);
camera.position.z = 5;

const scene = new Transform();

const geometry = new Box(gl);
const program = new Program(gl, {
    vertex: `
        attribute vec3 position;
        uniform mat4 modelViewMatrix;
        uniform mat4 projectionMatrix;
        void main() {
            gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
        }
    `,
    fragment: `
        void main() {
            gl_FragColor = vec4(1.0);
        }
    `,
});

const mesh = new Mesh(gl, { geometry, program });
mesh.setParent(scene);

function update() {
    requestAnimationFrame(update);
    mesh.rotation.y += 0.01;
    renderer.render({ scene, camera });
}
update();

Creating a custom geometry:

import { Geometry, Program, Mesh } from 'ogl';

const geometry = new Geometry(gl, {
    position: { size: 3, data: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0]) },
    uv: { size: 2, data: new Float32Array([0, 0, 1, 0, 1, 1]) },
    index: { data: new Uint16Array([0, 1, 2]) },
});

const program = new Program(gl, {
    vertex: `
        attribute vec3 position;
        attribute vec2 uv;
        varying vec2 vUv;
        void main() {
            vUv = uv;
            gl_Position = vec4(position, 1.0);
        }
    `,
    fragment: `
        varying vec2 vUv;
        void main() {
            gl_FragColor = vec4(vUv, 0.0, 1.0);
        }
    `,
});

const mesh = new Mesh(gl, { geometry, program });

Getting Started

  1. Install OGL using npm:

    npm install ogl
    
  2. Import the necessary components in your JavaScript file:

    import { Renderer, Camera, Transform, Box, Program, Mesh } from 'ogl';
    
  3. Create a basic scene and add it to your HTML:

    const renderer = new Renderer();
    const gl = renderer.gl;
    document.body.appendChild(gl.canvas);
    
    const camera = new Camera(gl);
    camera.position.z = 5;
    
    const scene = new Transform();
    
    // Add meshes and other objects to the scene
    
    function update() {
        requestAnimationFrame(update);
        renderer.render({ scene, camera });
    }
    update();
    
  4. Refer to the OGL documentation for more advanced usage and features.

Competitor Comparisons

101,622

JavaScript 3D Library.

Pros of Three.js

  • Extensive documentation and large community support
  • Wide range of features and built-in geometries
  • Robust ecosystem with numerous plugins and extensions

Cons of Three.js

  • Larger file size and potentially slower performance for simpler projects
  • Steeper learning curve due to its comprehensive nature
  • More complex setup for basic scenes compared to OGL

Code Comparison

Three.js basic scene setup:

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);

OGL basic scene setup:

const renderer = new Renderer();
const gl = renderer.gl;
const camera = new Camera(gl);
const scene = new Transform();

Three.js offers a more comprehensive set of features and extensive community support, making it suitable for complex 3D projects. However, this comes at the cost of a larger file size and potentially steeper learning curve. OGL, on the other hand, provides a more lightweight and performance-focused approach, which can be beneficial for simpler projects or when optimization is a priority. The code comparison demonstrates that OGL has a more concise setup process for basic scenes, while Three.js requires more initial configuration but offers more built-in functionality.

43,513

The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.

Pros of PixiJS

  • More comprehensive and feature-rich 2D rendering engine
  • Larger community and ecosystem with extensive plugins and extensions
  • Better suited for complex 2D games and interactive applications

Cons of PixiJS

  • Heavier library size compared to OGL's lightweight approach
  • May have a steeper learning curve for beginners
  • Less optimized for pure WebGL performance compared to OGL

Code Comparison

PixiJS example:

const app = new PIXI.Application();
document.body.appendChild(app.view);
const sprite = PIXI.Sprite.from('image.png');
app.stage.addChild(sprite);

OGL example:

const renderer = new Renderer();
const gl = renderer.gl;
const scene = new Transform();
const mesh = new Mesh(gl, { geometry, program });
scene.addChild(mesh);

PixiJS focuses on high-level abstractions for 2D rendering, while OGL provides a more low-level approach to WebGL, giving developers greater control over the rendering process. PixiJS is ideal for complex 2D projects, while OGL is better suited for lightweight 3D applications or when fine-grained WebGL control is required.

5,213

👑 Functional WebGL

Pros of regl

  • More flexible and lower-level API, allowing for greater control over WebGL rendering
  • Extensive documentation and examples, making it easier for developers to learn and use
  • Supports both WebGL 1 and WebGL 2, providing broader compatibility

Cons of regl

  • Steeper learning curve due to its lower-level nature
  • Requires more boilerplate code for basic setups compared to OGL
  • Less focus on 3D-specific features, which may require additional implementation

Code Comparison

OGL example:

const geometry = new Geometry(gl, {
  position: {size: 3, data: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0])},
});
const program = new Program(gl, {vertex, fragment});
const mesh = new Mesh(gl, {geometry, program});

regl example:

const drawTriangle = regl({
  frag: `void main() { gl_FragColor = vec4(1, 0, 0, 1); }`,
  vert: `attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1); }`,
  attributes: { position: [[-1, -1], [0, 1], [1, -1]] },
  count: 3
});
drawTriangle();

A lightweight 3D physics engine written in JavaScript.

Pros of cannon.js

  • Specialized physics engine with advanced simulation capabilities
  • Extensive documentation and examples for physics-based applications
  • Active community and longer development history

Cons of cannon.js

  • Focused solely on physics, requiring additional libraries for rendering
  • Potentially higher performance overhead for complex simulations
  • Less frequent updates and maintenance in recent years

Code Comparison

cannon.js (Physics simulation):

const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);

const sphereShape = new CANNON.Sphere(0.5);
const sphereBody = new CANNON.Body({
  mass: 5,
  shape: sphereShape
});
world.addBody(sphereBody);

ogl (3D rendering):

const geometry = new Geometry(gl, {
  position: {size: 3, data: new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0])},
});
const program = new Program(gl, {
  vertex,
  fragment,
});
const mesh = new Mesh(gl, {geometry, program});

Summary

cannon.js is a dedicated physics engine offering robust simulation capabilities, while ogl is a lightweight WebGL framework focused on 3D rendering. cannon.js excels in physics-based applications but requires additional rendering libraries. ogl provides efficient 3D graphics rendering but lacks built-in physics simulation. The choice between them depends on project requirements, with cannon.js being more suitable for physics-heavy applications and ogl for graphics-oriented projects.

🇨🇭 A React renderer for Three.js

Pros of react-three-fiber

  • Seamless integration with React ecosystem and component-based architecture
  • Declarative approach to 3D rendering, simplifying complex scene creation
  • Large community and extensive ecosystem of add-ons and helpers

Cons of react-three-fiber

  • Steeper learning curve for developers unfamiliar with React
  • Potential performance overhead due to React's reconciliation process
  • Less flexibility for low-level WebGL operations compared to OGL

Code Comparison

react-three-fiber:

function Scene() {
  return (
    <Canvas>
      <mesh>
        <boxGeometry args={[1, 1, 1]} />
        <meshStandardMaterial color="hotpink" />
      </mesh>
    </Canvas>
  );
}

OGL:

const geometry = new Box(gl);
const material = new Program(gl, {
  vertex,
  fragment,
  uniforms: {
    color: { value: [1, 0.5, 0.5] },
  },
});
const mesh = new Mesh(gl, { geometry, material });

Both libraries offer powerful 3D rendering capabilities, but cater to different developer preferences and use cases. react-three-fiber excels in React-based applications with its declarative approach, while OGL provides more direct control over WebGL operations for performance-critical scenarios.

Babylon.js is a powerful, beautiful, simple, and open game and rendering engine packed into a friendly JavaScript framework.

Pros of Babylon.js

  • More comprehensive and feature-rich 3D engine with advanced rendering capabilities
  • Larger community and extensive documentation, making it easier to find support and resources
  • Built-in physics engine and support for various file formats

Cons of Babylon.js

  • Larger file size and potentially higher performance overhead for simpler projects
  • Steeper learning curve due to its extensive feature set
  • Less suitable for lightweight or minimalist applications

Code Comparison

Babylon.js:

const scene = new BABYLON.Scene(engine);
const camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 5, -10), scene);
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter: 2}, scene);

OGL:

const scene = new Transform();
const camera = new Camera(gl);
const light = new Vec3(0, 1, 0);
const geometry = new Sphere(gl);
const sphere = new Mesh(gl, {geometry});

OGL is more lightweight and minimalist, focusing on core WebGL functionality. It's ideal for developers who want fine-grained control and a smaller footprint. Babylon.js offers a more comprehensive set of features and tools, making it suitable for complex 3D applications and games, but at the cost of a larger file size and potentially higher resource usage.

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

OGL

OGL

version license size

Minimal WebGL library.


See the Examples!

OGL is a small, effective WebGL library aimed at developers who like minimal layers of abstraction, and are interested in creating their own shaders.

Written in es6 modules with zero dependencies, the API shares many similarities with ThreeJS, however it is tightly coupled with WebGL and comes with much fewer features.

In its design, the library does the minimum abstraction necessary, so devs should still feel comfortable using it in conjunction with native WebGL commands.

Keeping the level of abstraction low helps to make the library easier to understand, extend, and also makes it more practical as a WebGL learning resource.

Install

Download

or

npm i ogl

or

yarn add ogl

Examples

Show me what you got! - Explore a comprehensive list of examples, with comments in the source code.

Inspired by the effectiveness of ThreeJS' examples, they will hopefully serve as reference for how to use the library, and to achieve a wide range of techniques.

Weight

Even though the source is modular, as a guide, below are the complete component download sizes.

ComponentSize (minzipped)
Core8kb
Math6kb
Extras15kb
Total29kb

With tree-shaking applied in a build step, one can expect the final size to be much lighter than the values above.

Usage

If installed amongst your project files, importing can be done from one single entry point.

import { ... } from './path/to/src/index.js';

Else if using a bundler or import maps with node modules, then import directly from the installed node module.

import { ... } from 'ogl';

By default, the ES source modules are loaded (src/index.js).

As another alternative, you could load from a CDN, using either the jsdelivr, unpkg or skypack services.

import { ... } from 'https://cdn.jsdelivr.net/npm/ogl';
import { ... } from 'https://unpkg.com/ogl';
import { ... } from 'https://cdn.skypack.dev/ogl';

If you take this route, I would highly recommend defining a specific version (append @x.x.x) to avoid code breaking, rather than fetching the latest version, as per the above links.

As a basic API example, below renders a spinning white cube.

import { Renderer, Camera, Transform, Box, Program, Mesh } from 'ogl';

{
    const renderer = new Renderer();
    const gl = renderer.gl;
    document.body.appendChild(gl.canvas);

    const camera = new Camera(gl);
    camera.position.z = 5;

    function resize() {
        renderer.setSize(window.innerWidth, window.innerHeight);
        camera.perspective({
            aspect: gl.canvas.width / gl.canvas.height,
        });
    }
    window.addEventListener('resize', resize, false);
    resize();

    const scene = new Transform();

    const geometry = new Box(gl);

    const program = new Program(gl, {
        vertex: /* glsl */ `
            attribute vec3 position;

            uniform mat4 modelViewMatrix;
            uniform mat4 projectionMatrix;

            void main() {
                gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
            }
        `,
        fragment: /* glsl */ `
            void main() {
                gl_FragColor = vec4(1.0);
            }
        `,
    });

    const mesh = new Mesh(gl, { geometry, program });
    mesh.setParent(scene);

    requestAnimationFrame(update);
    function update(t) {
        requestAnimationFrame(update);

        mesh.rotation.y -= 0.04;
        mesh.rotation.x += 0.03;

        renderer.render({ scene, camera });
    }
}

Here you can play with the above template live in a codesandbox https://codesandbox.io/s/ogl-5i69p

For a simpler use, such as a full-screen shader, more of the core can be omitted as a scene graph (Transform) and projection matrices (Camera) are not necessary. We'll also show how to easily create custom geometry.

import { Renderer, Geometry, Program, Mesh } from 'ogl';

{
    const renderer = new Renderer({
        width: window.innerWidth,
        height: window.innerHeight,
    });
    const gl = renderer.gl;
    document.body.appendChild(gl.canvas);

    // Triangle that covers viewport, with UVs that still span 0 > 1 across viewport
    const geometry = new Geometry(gl, {
        position: { size: 2, data: new Float32Array([-1, -1, 3, -1, -1, 3]) },
        uv: { size: 2, data: new Float32Array([0, 0, 2, 0, 0, 2]) },
    });
    // Alternatively, you could use the Triangle class.

    const program = new Program(gl, {
        vertex: /* glsl */ `
            attribute vec2 uv;
            attribute vec2 position;

            varying vec2 vUv;

            void main() {
                vUv = uv;
                gl_Position = vec4(position, 0, 1);
            }
        `,
        fragment: /* glsl */ `
            precision highp float;

            uniform float uTime;

            varying vec2 vUv;

            void main() {
                gl_FragColor.rgb = vec3(0.8, 0.7, 1.0) + 0.3 * cos(vUv.xyx + uTime);
                gl_FragColor.a = 1.0;
            }
        `,
        uniforms: {
            uTime: { value: 0 },
        },
    });

    const mesh = new Mesh(gl, { geometry, program });

    requestAnimationFrame(update);
    function update(t) {
        requestAnimationFrame(update);

        program.uniforms.uTime.value = t * 0.001;

        // Don't need a camera if camera uniforms aren't required
        renderer.render({ scene: mesh });
    }
}

Structure

In an attempt to keep things light and modular, the library is split up into three components: Math, Core, and Extras.

The Math component is an extension of gl-matrix, providing instancable classes that extend Array for each of the module types. 8kb when gzipped, it has no dependencies and can be used separately.

The Core is made up of the following:

  • Geometry.js
  • Program.js
  • Renderer.js
  • Camera.js
  • Transform.js
  • Mesh.js
  • Texture.js
  • RenderTarget.js

Any additional layers of abstraction will be included as Extras, and not part of the core as to reduce bloat. These provide a wide breadth of functionality, ranging from simple to advanced.

Unlicense

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to https://unlicense.org

NPM DownloadsLast 30 Days