Last active
November 28, 2022 23:13
-
-
Save 8Observer8/c4065053574a0f60e4feffbd4b0bdfa4 to your computer and use it in GitHub Desktop.
Import glMatrix and a simple triangle in WebGL
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Dog. WebGL, JavaScript</title> | |
</head> | |
<body> | |
<canvas id="renderCanvas" width="400" height="300"></canvas> | |
<script type="importmap"> | |
{ | |
"imports": { | |
"gl-matrix": "https://cdn.skypack.dev/[email protected]" | |
} | |
} | |
</script> | |
<script type="module"> | |
import { vec3 } from "gl-matrix"; | |
const gl = document.getElementById("renderCanvas").getContext("webgl"); | |
gl.clearColor(0.2, 0.2, 0.2, 1); | |
const vertShaderSrc = | |
`attribute vec3 aPosition; | |
void main() { | |
gl_Position = vec4(aPosition, 1.0); | |
}`; | |
const fragShaderSrc = | |
`precision mediump float; | |
void main() { | |
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); | |
} | |
`; | |
const vShader = gl.createShader(gl.VERTEX_SHADER); | |
gl.shaderSource(vShader, vertShaderSrc); | |
gl.compileShader(vShader); | |
// console.log(gl.getShaderInfoLog(vShader)); | |
const fShader = gl.createShader(gl.FRAGMENT_SHADER); | |
gl.shaderSource(fShader, fragShaderSrc); | |
gl.compileShader(fShader); | |
// console.log(gl.getShaderInfoLog(fShader)); | |
const program = gl.createProgram(); | |
gl.attachShader(program, vShader); | |
gl.attachShader(program, fShader); | |
gl.bindAttribLocation(program, 0, "aPosition"); | |
gl.linkProgram(program); | |
// console.log(gl.getProgramInfoLog(program)); | |
gl.useProgram(program); | |
const vertPositions = [ | |
-0.5, -0.5, 0, | |
0.5, -0.5, 0, | |
0, 0.5, 0]; | |
const vertPosBuffer = gl.createBuffer(); | |
gl.bindBuffer(gl.ARRAY_BUFFER, vertPosBuffer); | |
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertPositions), | |
gl.STATIC_DRAW); | |
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0); | |
gl.enableVertexAttribArray(0); | |
gl.clear(gl.COLOR_BUFFER_BIT); | |
gl.drawArrays(gl.TRIANGLES, 0, 3); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment