Skip to content

Instantly share code, notes, and snippets.

@maxsei
Last active February 21, 2024 18:22
Show Gist options
  • Select an option

  • Save maxsei/1358ecc081b6e5a7d882e1b8574d9003 to your computer and use it in GitHub Desktop.

Select an option

Save maxsei/1358ecc081b6e5a7d882e1b8574d9003 to your computer and use it in GitHub Desktop.
Drawing overlapping rectangles with webgl
function drawRectangles(gl) {
// Create vertex buffer and bind it.
const vertices = new Float32Array(4 * 2);
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
// Create vertex shader
const vertexShaderCode = `
attribute vec2 coordinates;
void main(void) {
gl_Position = vec4(coordinates, 0.0, 1.0);
}`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderCode);
gl.compileShader(vertexShader);
// Create fragment shader
const fragmentShaderCode = `
precision mediump float;
uniform vec4 color;
void main(void) {
gl_FragColor = color;
}`;
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderCode);
gl.compileShader(fragmentShader);
// Create shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
// Specify vertex position attribute
const coord = gl.getAttribLocation(shaderProgram, "coordinates");
gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coord);
// Set blending mode
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
// Draw both rectangles together
gl.clearColor(0.0, 1.0, 0.0, 1.0); // green
gl.clear(gl.COLOR_BUFFER_BIT);
const colorLocation = gl.getUniformLocation(shaderProgram, "color");
// Draw first rectangle (red)
vertices.set([
-0.75,
0.75, // tl
-0.75,
-0.75, // bl
0.75,
0.75, // tr
0.75,
-0.75, // br
]);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
gl.uniform4fv(colorLocation, [1.0, 0.0, 0.0, 1.0]);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
// Draw second rectangle (blue)
vertices.set([
-0.25,
0.25, // tl
-0.25,
-0.25, // bl
0.25,
0.25, // tr
0.25,
-0.25, // br
]);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
gl.uniform4fv(colorLocation, [0.0, 0.0, 1.0, 1.0]);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
// Initialize WebGL context
const canvas = document.getElementById("myCanvas");
const gl = canvas.getContext("webgl2");
drawRectangles(gl);
// Clear after one second
setTimeout(()=> {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment