Skip to content

Instantly share code, notes, and snippets.

@lorenzored98
Last active May 4, 2023 18:56
Show Gist options
  • Save lorenzored98/56dce409d510417042ccdc97c1f3f72a to your computer and use it in GitHub Desktop.
Save lorenzored98/56dce409d510417042ccdc97c1f3f72a to your computer and use it in GitHub Desktop.
Quad without vertex buffer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Quad without vertex buffer</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body,
#app {
width: 100%;
height: 100%;
}
#app {
display: flex;
justify-content: center;
align-items: center;
}
canvas {
display: block;
}
</style>
</head>
<body>
<div id="app">
<canvas id="canvas"></canvas>
</div>
</body>
<script>
const app = document.getElementById("app");
const canvas = document.getElementById("canvas");
const w = 600;
const h = 400;
canvas.width = w;
canvas.height = h;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
const gl = canvas.getContext("webgl2");
const vs = `#version 300 es
out vec2 vUv;
void main() {
vec2 uv = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
vec2 pos = uv * 2.0 - 1.0;
// We can also have arbitrary transforms
#if 0
pos *= 0.3;
pos *= mat2(1.0, -0.7, 0.7, 1.0);
pos += vec2(0.3, -0.4);
#endif
gl_Position = vec4(pos, 0.0, 1.0);
vUv = uv;
}
`;
const fs = `#version 300 es
precision highp float;
in vec2 vUv;
out vec4 outColor;
void main() {
outColor = vec4(vUv, 1.0, 1.0);
}
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vs);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fs);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
function main() {
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
window.requestAnimationFrame(main);
}
main();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment