Created
August 28, 2025 21:32
-
-
Save greggman/625e82cadb4c212df6a924dd8adda7a2 to your computer and use it in GitHub Desktop.
WebGL: Simplest Hello Triangle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
:root { | |
color-scheme: light dark; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas></canvas> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const canvas = document.querySelector('canvas'); | |
const gl = canvas.getContext('webgl2'); | |
function createShader(gl, type, src) { | |
const shader = gl.createShader(type); | |
gl.shaderSource(shader, src); | |
gl.compileShader(shader); | |
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { | |
throw new Error(gl.getShaderInfoLog(shader)); | |
} | |
return shader; | |
} | |
const program = gl.createProgram();; | |
gl.attachShader(program, createShader(gl, gl.VERTEX_SHADER, `#version 300 es | |
void main() { | |
vec2 pos[3]; | |
pos[0] = vec2( 0, 1); | |
pos[1] = vec2(-1,-1); | |
pos[2] = vec2( 1,-1); | |
gl_Position = vec4(pos[gl_VertexID], 0, 1); | |
} | |
`)); | |
gl.attachShader(program, createShader(gl, gl.FRAGMENT_SHADER, `#version 300 es | |
precision highp float; | |
out vec4 fragColor; | |
void main() { | |
fragColor = vec4(1, 0, 0, 1); | |
} | |
`)); | |
gl.linkProgram(program); | |
gl.clearColor(0, 0, 1, 1); | |
gl.clear(gl.COLOR_BUFFER_BIT); | |
gl.useProgram(program); | |
gl.drawArrays(gl.TRIANGLES, 0, 3); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"name":"WebGL: Simplest Hello Triangle","settings":{},"filenames":["index.html","index.css","index.js"]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment