Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>WebGL</title>
- <style>html, body { margin: 0; padding: 0; height: 100%; background-color: #293039; display: flex; justify-content: center; align-items: center; }</style>
- </head>
- <body>
- <canvas id="canvas" width="640" height="480"></canvas>
- <script>
- const canvas = document.getElementById('canvas');
- const gl = canvas.getContext('webgl');
- // Create and compile a vertex shader.
- const vertexShader = gl.createShader(gl.VERTEX_SHADER);
- gl.shaderSource(vertexShader, `
- attribute vec2 position;
- void main() {
- gl_Position = vec4(position, 0.0, 1.0);
- }
- `);
- gl.compileShader(vertexShader);
- // Create and compile a fragment shader.
- const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
- gl.shaderSource(fragmentShader, `
- void main(void) {
- gl_FragColor = vec4(0, 0.77, 0.8, 1.0);
- }
- `);
- gl.compileShader(fragmentShader);
- // Compile, link and enable the shader program.
- const program = gl.createProgram();
- gl.attachShader(program, vertexShader);
- gl.attachShader(program, fragmentShader);
- gl.linkProgram(program);
- gl.useProgram(program);
- // Defines a 2D quad in clip-space using two triangles in counter-clockwise winding order.
- // (-1, +1) TL ┌─────┐ TR (+1, +1)
- // │ ╲ │
- // │ ╲ │
- // (-1, -1) BL └─────┘ BR (+1, -1)
- const dimensions = 2;
- const vertices = new Float32Array([
- // Top right triangle.
- -1, +1, // TL
- +1, -1, // BR
- +1, +1, // TR
- // Bottom left triangle.
- -1, +1, // TL
- -1, -1, // BL
- +1, -1, // BR
- ]);
- // Create a buffer on the GPU, bind to it and upload the data.
- const positionBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
- // Get a reference to the position attribute, enable it, and point the attribute to the uploaded position buffer.
- const positionAttribute = gl.getAttribLocation(program, 'position');
- gl.enableVertexAttribArray(positionAttribute);
- gl.vertexAttribPointer(positionAttribute, dimensions, gl.FLOAT, false, 0, 0);
- // Render to the canvas.
- gl.drawArrays(gl.TRIANGLES, 0, vertices.length / dimensions);
- </script>
- </html>
Add Comment
Please, Sign In to add comment