Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas id="canvas" width="1000px" height="500px">not surpport canvas</canvas>

<script type="notjs" id="vertex-shader">
      attribute vec2 a_position;

      uniform vec2 u_resolution;

      void main() {
         // convert the rectangle points from pixels to 0.0 to 1.0

         //mat2 T = mat2(1.0, 3.0, 2.0, 1.0);
         //vec2 zeroToOne = T * a_position / u_resolution;
         vec2 zeroToOne =  a_position / u_resolution;

         // convert from 0->1 to 0->2
         vec2 zeroToTwo = zeroToOne * 2.0;

         // convert from 0->2 to -1->+1 (clipspace)
         vec2 clipSpace = zeroToTwo - 1.0;

         gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
      }
    </script>

    <script id="fragment-shader" type="notjs">
      precision mediump float;

      uniform vec4 u_color;

      void main() {
        gl_FragColor = u_color;
      }
    </script>

    <script>
      function d2_f(x, y, width, height, thickness) {
        const data = [
          // left column
          x,
          y,
          x + thickness,
          y,
          x,
          y + height,
          x,
          y + height,
          x + thickness,
          y,
          x + thickness,
          y + height,

          // top rung
          x + thickness,
          y,
          x + width,
          y,
          x + thickness,
          y + thickness,
          x + thickness,
          y + thickness,
          x + width,
          y,
          x + width,
          y + thickness,

          // middle rung
          x + thickness,
          y + thickness * 2,
          x + (width * 2) / 3,
          y + thickness * 2,
          x + thickness,
          y + thickness * 3,
          x + thickness,
          y + thickness * 3,
          x + (width * 2) / 3,
          y + thickness * 2,
          x + (width * 2) / 3,
          y + thickness * 3,
        ];

        return new Mesh({ vertices: data, dimension: 2 });
      }

      function loadShader(gl, type, source) {
        const shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
          const err = "An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader);
          gl.deleteShader(shader);
          throw err;
        }
        return shader;
      }

      function initProgram(gl, name) {
        let vShaderId = "vertex-shader";
        let fShaderId = "fragment-shader";
        if (name !== "default") {
          vShaderId += "-" + name;
          fShaderId += "-" + name;
        }
        console.log(vShaderId);
        const vertexShaderSource = document.getElementById(vShaderId).text;
        const fragShaderSource = document.getElementById(fShaderId).text;

        const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
        const fragShader = loadShader(gl, gl.FRAGMENT_SHADER, fragShaderSource);

        const program = gl.createProgram();
        gl.attachShader(program, vertexShader);
        gl.attachShader(program, fragShader);
        gl.linkProgram(program);

        return program;
      }

      class Timing {
        constructor() {
          this.listeners = [];
          this.start();
        }

        listen(handler) {
          this.listeners.push({ handler, listenAt: new Date().getTime() });
          return () => {
            this.listeners = this.listeners.filter((x) => x !== handler);
          };
        }

        start() {
          this.startAt = new Date().getTime();
          this.run();
        }

        run = () => {
          const current = new Date().getTime();
          this.listeners.forEach(({ handler, listenAt }) => {
            handler({
              diff: current - listenAt,
            });
          });
          requestAnimationFrame(this.run);
        };
      }

      class GLVertexBuffer {
        constructor(name, data, dimension = 3, mode) {
          this.dimension = dimension;
          this.gl = RenderContext.getGL();
          this.name = name;
          /* 初始化Buffer */
          this.buffer = this.gl.createBuffer();
          this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffer);
          this.gl.bufferData(this.gl.ARRAY_BUFFER, data, mode || this.gl.STATIC_DRAW);
          this.data = data;
        }

        associate() {
          this.location = this.gl.getAttribLocation(RenderContext.getProgram(), this.name);
          this.gl.enableVertexAttribArray(this.location);
          this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffer);
          const type = this.gl.FLOAT;
          const normalized = false;
          const stride = 0;
          const offset = 0;
          this.gl.vertexAttribPointer(this.location, this.dimension, type, normalized, stride, offset);
        }
      }

      class Mesh {
        constructor({ vertices, indices = null, dimension = 3, colors = null, texCoords, norms }) {
          this.dimension = dimension;
          this.vertices = vertices;
          this.indices = indices;
          this.colors = colors;
          this.norms = norms;
          this.texCoords = texCoords;
          this.gl = RenderContext.getGL();
          this.customVerticesBuffer = [];

          this.vertexBuffer = new GLVertexBuffer("a_position", new Float32Array(vertices), dimension);

          if (this.colors) {
            this.colorsBuffer = new GLVertexBuffer("a_color", new Float32Array(colors), dimension);
          }

          if (this.indices) {
            this.indicesBuffer = new GLIndexBuffer(new Uint16Array(this.indices), dimension);
          }

          if (this.texCoords) {
            this.texturesBuffer = new GLVertexBuffer("a_texcoord", new Float32Array(texCoords), 2);
          }

          if (this.norms) {
            this.normsBuffer = new GLVertexBuffer("a_norm", new Float32Array(norms), 3);
          }
        }

        addVertexBuffer(name, data, dimension) {
          this.customVerticesBuffer.push(new GLVertexBuffer(name, data, dimension));
        }

        draw() {
          const gl = this.gl;

          this.vertexBuffer.associate();
          this.colorsBuffer && this.colorsBuffer.associate();
          this.indicesBuffer && this.indicesBuffer.associate();
          this.texCoords && this.texturesBuffer.associate();
          this.normsBuffer && this.normsBuffer.associate();

          this.customVerticesBuffer.forEach((buffer) => {
            buffer.associate();
          });

          if (this.indicesBuffer) {
            gl.drawElements(gl.TRIANGLES, this.indices.length, gl.UNSIGNED_SHORT, 0);
          } else {
            gl.drawArrays(gl.TRIANGLES, 0, this.vertices.length / this.dimension);
          }
        }
      }

      class RenderContext {
        static gl = null;
        static timing = null;
        static programs = {};

        static init() {
          if (RenderContext.gl) {
            return;
          }
          const gl = document.getElementById("canvas").getContext("webgl");
          gl.canvas.width = gl.canvas.clientWidth;
          gl.canvas.height = gl.canvas.clientHeight;
          RenderContext.gl = gl;
          RenderContext.timing = new Timing();
          RenderContext.aspect = gl.canvas.width / gl.canvas.height;
          RenderContext.currentProgram = null;
        }

        static initProgram(name = "default") {
          const gl = RenderContext.gl;
          if (!RenderContext.programs[name]) {
            const program = initProgram(gl, name);
            RenderContext.programs[name] = program;
          }
          if (name === "default") {
            RenderContext.gl.useProgram(RenderContext.programs["default"]);
          }
        }

        static getAspect() {
          return RenderContext.aspect;
        }

        static getGL() {
          this.init();
          return RenderContext.gl;
        }

        static getTiming() {
          this.init();
          return RenderContext.timing;
        }

        static getProgram() {
          this.init();
          if (!RenderContext.currentProgram) {
            this.initProgram("default");
            RenderContext.currentProgram = RenderContext.programs["default"];
          }
          return RenderContext.currentProgram;
        }

        static switchProgram(name) {
          this.init();
          this.initProgram(name);
          RenderContext.currentProgram = RenderContext.programs[name];
          RenderContext.gl.useProgram(RenderContext.currentProgram);
        }
      }

      class Model {
        constructor(mesh, dimensions = 3, level = 0) {
          this.mesh = mesh;
          this.worldMatrix = dimensions === 3 ? identity4d() : identity3d();
          this.unitMatrix = dimensions === 3 ? identity4d() : identity3d();

          this.gl = RenderContext.getGL();
          this.children = [];
          this.level = level;
          this.textures = [];
        }

        setVectorUniform(name, value) {
          const position = this.gl.getUniformLocation(RenderContext.getProgram(), name);
          if (value.length === 2) {
            this.gl.uniform2fv(position, value);
          } else if (value.length === 3) {
            this.gl.uniform3fv(position, value);
          } else if (value.length === 4) {
            this.gl.uniform4fv(position, value);
          }
        }

        setFloatUniform(name, value) {
          const position = this.gl.getUniformLocation(RenderContext.getProgram(), name);
          this.gl.uniform1f(position, value);
        }

        setMatrixUniform(name, value) {
          const position = this.gl.getUniformLocation(RenderContext.getProgram(), name);
          if (value.length === 4) {
            this.gl.uniformMatrix2fv(position, false, value);
          } else if (value.length === 9) {
            this.gl.uniformMatrix3fv(position, false, value);
          } else if (value.length === 16) {
            this.gl.uniformMatrix4fv(position, false, value);
          }
        }

        setUnitMatrix(unitMatrix) {
          this.unitMatrix = unitMatrix;
        }

        setWorldMatrix(worldMatrix) {
          this.worldMatrix = worldMatrix;
        }

        addChild(model) {
          model.parent = this;
          this.children.push(model);
        }

        addTextureImage(src) {
          this.textures.push(new ImageTexture(src));
        }

        /**
         * 递归更新世界矩阵
         * @param {*} parentWorldMatrix
         * @param {*} parentUnitMatrix
         */
        updateMatrix(parentWorldMatrix, parentUnitMatrix) {
          if (parentUnitMatrix) {
            // pworld * punit * unit * vec4
            // glsl ->
            // A(T) * B(T)
            this.worldMatrix = multiply4d(parentUnitMatrix, parentWorldMatrix);
          }
          for (let child of this.children) {
            child.updateMatrix(this.worldMatrix, this.unitMatrix);
          }
        }

        draw() {
          this.setMatrixUniform("u_unit", this.unitMatrix);
          this.setMatrixUniform("u_world", this.worldMatrix);

          if (this.mesh) {
            this.textures.forEach((texture) => {
              texture.associate(RenderContext.getProgram());
            });
            this.mesh.draw();
          }

          this.children.forEach((child) => child.draw());
        }
      }

      function identity4d() {
        return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
      }

      function main() {
        const gl = document.getElementById("canvas").getContext("webgl");
        console.log(gl, gl.DEPTH_TEST, gl.LEQUAL);

        gl.enable(gl.DEPTH_TEST);
        gl.depthFunc(gl.LEQUAL);

        gl.clearDepth(1.0);
        gl.viewport(0.0, 0.0, canvas.width, canvas.height);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        const mesh = d2_f(100, 100, 100, 150, 30);
        const model = new Model(mesh);

        model.setVectorUniform("u_color", [Math.random(), Math.random(), Math.random(), 1.0]);
        model.setVectorUniform("u_resolution", [gl.canvas.width, gl.canvas.height]);

        model.draw();
      }

      main();
    </script>
              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console