javascript - WebGL draw through indices -
i new in webgl, trying draw square using 2 triangles , indices. not getting right. have been looking @ codes , examples missing something. trying keep things simple.
<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>
the background appears, square not.
the downloaded codes run know error in code only.
your gl.vertexattribpointer incorrect. created float32array telling webgl use unsigned shorts , mispelled itemsize.
change gl.vertexattribpointer(program.avertexposition, itemsize, gl.float, false, 0, 0);
, works me.
Comments
Post a Comment