Skip to content

Instantly share code, notes, and snippets.

@ahmadyogi543
Created May 9, 2023 02:08
Show Gist options
  • Save ahmadyogi543/67366ab6e8cf987c34866ba0f86b28d7 to your computer and use it in GitHub Desktop.
Save ahmadyogi543/67366ab6e8cf987c34866ba0f86b28d7 to your computer and use it in GitHub Desktop.
P4 - Buffer Object
const VSHADER_SOURCE = `
attribute vec4 a_Position;
void main() {
gl_Position = a_Position;
gl_PointSize = 10.0;
}`;
const FSHADER_SOURCE = `
precision mediump float;
uniform vec4 u_FragColor;
void main() {
gl_FragColor = u_FragColor;
}`;
function initVertexBuffers(gl, vertices) {
const vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.error("Gagal dalam membuat buffer object!");
return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
const a_Position = gl.getAttribLocation(gl.program, "a_Position");
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Position);
const n = Math.floor(vertices.length / 2);
return n;
}
function setColor(gl, color) {
const u_FragColor = gl.getUniformLocation(gl.program, "u_FragColor");
gl.uniform4f(u_FragColor, ...color);
}
function drawShape(gl, mode, vertices) {
const n = initVertexBuffers(gl, vertices);
if (n < 0) {
alert("Gagal dalam menginisiasi buffer object!");
return;
}
gl.drawArrays(mode, 0, n);
}
function main() {
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");
if (!initShaderProgram(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
alert("Gagal dalam menginisialisasi shader program!");
return;
}
gl.useProgram(gl.program);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
const vertices = new Float32Array([
0.0, 0.0,
0.5, 0.5,
0.0, 0.7,
-0.5, 0.5,
]);
setColor(gl, [1.0, 0.0, 0.0, 1.0]);
drawShape(gl, gl.TRIANGLE_FAN, vertices);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment