As a novice in WebGL, my goal is to create a square using two triangles and indices. Unfortunately, I seem to be missing something in my implementation. Despite reviewing various codes and examples, the issue persists. My focus is on maintaining simplicity within my code.
<html>
<head>
<meta charset="utf-8"/>
<script id="vertex" type="x-shader">
attribute vec2 aVertexPosition;
void main() {
gl_Position = vec4(aVertexPosition, 0.0, 1.0);
}
</script>
<script id="fragment" type="x-shader">
#ifdef GL_ES
precision highp float;
#endif
uniform vec4 uColor;
void main() {
gl_FragColor = uColor;
}
</script>
<script type="text/javascript">
function init(){
var canvas = document.getElementById("mycanvas");
var gl = canvas.getContext("experimental-webgl");
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.5, 0.0, 0.2, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
var v = document.getElementById("vertex").firstChild.nodeValue;
var f = document.getElementById("fragment").firstChild.nodeValue;
var vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, v);
gl.compileShader(vs);
var fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, f);
gl.compileShader(fs);
var program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
var vertices = [ -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5];
var indices = [ 3, 2, 1, 3, 1, 0 ]
var vbuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
var ebuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ebuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
var itemSize = 2;
var numItems = vertices.length / itemSize;
gl.useProgram(program);
program.uColor = gl.getUniformLocation(program, "uColor");
gl.uniform4fv(program.uColor, [0.0, 0.3, 0.0, 1.0]);
program.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
gl.enableVertexAttribArray(program.aVertexPosition);
gl.vertexAttribPointer(program.aVertexPosition, itemsize, gl.UNSIGNED_SHORT, false, 0, 0);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
}
</script>
</head>
<body onload="init()">
<canvas id="mycanvas" width="800" height="500"></canvas>
</body>
While the background loads successfully, the desired square fails to appear on the canvas.
I have confirmed that the downloaded codes execute correctly, indicating that the issue lies within my own code.