Drawing with WebGL using index values

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.

Answer №1

The issue lies with your gl.vertexAttribPointer function. You initialized a Float32Array, but incorrectly specified unsigned shorts and also made a typo with itemSize.

Try updating it to

gl.vertexAttribPointer(program.aVertexPosition, itemSize, gl.FLOAT, false, 0, 0);
. This adjustment resolved the problem for me.

Answer №2

Your array of vertices was incomplete, missing a coordinate for the last element. It's essential that arrays of vertices have 3 coordinates for each vertex and are multiples of 3.

In your indices array, the points representing vertices should be connected as triangles to display your geometry properly. Give this a try, it should work fine.

function setup(){
    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, 0, 0,  0.5, 0, 0.5, 0, 0];
    var indices = [ 0, 1, 2 ]

    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, 3, gl.UNSIGNED_SHORT, 0);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

Cast your vote once for each post within the Angular application

Currently, users are only able to vote up or down once in general. I would like to allow users to vote up or down once per post. <div ng-repeat="post in posts | orderBy:'-upvotes'"> <span class="glyphicon glyphicon-thumbs-up" ...

Is it possible for Ajax to actually make GET requests to the server, and if it does, why doesn't it appear in Firebug?

I have a LAMP setup on my Ubuntu and I am attempting to use Ajax to print the output in an unordered list. However, I am not seeing any results and there are no server calls showing up in Firebug. Here is the HTML file where the call is made: <!DOCTYP ...

Utilizing fibrous in node.js to efficiently fetch data from the request library

I am struggling to efficiently utilize the fibrous library in conjunction with request for obtaining the body of an HTTP request synchronously. However, I have encountered difficulties in managing the flow. In order to address this issue, I created a simp ...

Update the ngView content on the fly

My project requires dynamic routes to be generated when specific URLs are requested in order to customize the view and display corresponding data uniformly. While adding manual routes with the same templateUrl and controller would have made this task simpl ...

Send the data to the web form along with the JSON information

I find myself in a situation where I am looking for alternative ways to pass data to a redirect page without using querystrings. Here is the current implementation on the Source Page: window.location = "invaliduser.aspx?u=" + encodeURI(username); Consi ...

Updating values within an ng-repeat loop by using the ng-change directive to increment or decrement

Below is an example code snippet that demonstrates a checkbox feature: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Welcome to LearnKode - A code learning platform</title> ...

Error: [BITFIELD_INVALID_RANGE]: The bitfield flag or number entered is not valid: 3214336

Currently working on a Discord Dashboard project, but encountering an unusual error: Invalid bitfield flag or number 3214336. This issue arises when attempting to retrieve the guilds that a user has MANAGE_GUILDS permission for. Below is the snippet of my ...

Begin 5 seconds after loading

First time attempting this task. My goal is to trigger the loading of an I have been trying to write a script for this, but it's not functioning as expected. HTML : <div id="div1"> <a id="single" href="#">Single Play</a> & ...

What is the best way to make a sticky floating sidebar that stays fixed while scrolling?

I'm facing a challenge on my website where I want a sidebar on the left to stay with the user as they scroll. The sidebar should scroll along with the user until it's 5px from the top of the page, at which point it should remain fixed in place. ...

When doctype is specified, `$(window).height()` will output the height of the document

Recently, I've encountered an issue where trying to retrieve the browser's window height using $(window).height() has been returning a significantly larger number, likely indicating the document height instead. It's strange because I've ...

I would appreciate your assistance with the hide button

Is there a way to hide a button after clicking on it? I would greatly appreciate your help! ...

Remove Vue Component from the styling of current application

We integrated a Vue component (using Vuetify) into our existing .NET MVC application. The issue we are facing is that the Vue component is inheriting all the CSS styles from the rest of the application. Here's a simplified version of the HTML structur ...

Can anyone provide examples of how RegisterClientScriptBlock parameters are used in practical situations?

https://i.sstatic.net/dVjHt.jpg I've always struggled to grasp the true purpose of using the Control, Type, and Key in this particular class. Typically, I would use it with: this, GetType(), "xx" however, now I am determined to gain a deeper unders ...

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

Array of class properties in Typescript

Is there a way to iterate through the properties of a class or a new object instance of that class when none of the properties are set? When I use Object.keys(), it returns an empty array because no properties have been initialized. How can I achieve this ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

Using jQuery to manipulate the radio button input's alternate content in HTML attributes

How can I use Jquery Attr.Radio Button click to write to the div with id #RadioDesc? <input type="radio" desc="sample description" class="AddText"> <script type="text/javascript"> $( document ).ready( function() { $("radio").click ...

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

How can jQuery be used to modify the values of 'title' and 'description'?

newList.addItem({ title: 'New York', description: 'The Big Apple' }); I want to update these details by clicking on a specific element. ...