6 Feb 2021

WebGL Simple Hello World Like Tutorial OR Example


We are going to see the WebGL example with 4 vertices.
Therefore, we have been provided 4 point over canvas accordingly WebGL Native Coordinate System.

 vertex = [ 
0.3, 0.0, 0.0, //right 
0.0, 0.3, 0.0, //top 
-0.3, 0.0, 0.0, //left 
0.0, -0.3, 0.0 //down
]; 

Creating WebGLBuffer object & Binding

Getting WebGLBuffer object by calling method createBuffer() on WebGLRendringContext. Next to Binding buffer  object to WebGL. providing buffer vertex data to WebGL.


buffer = gl.createBuffer();  gl.bindBuffer(gl.ARRAY_BUFFER, buffer); 
gl.bufferData(gl.ARRAY_BUFFER , new Float32Array(vertex), gl.STATIC_DRAW); 

WebGLShader

Vertex Shader


vertexCode = "attribute vec3 coordinates;"+ "void main(){"+ "gl_Position = vec4(coordinates, 1.0);" + " gl_PointSize = 10.0;"+ " }";

vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader , vertexCode); gl.compileShader(vertexShader);

Fragment Shader / Pixel Shader

fragmentCode = "void main(){"+ " gl_FragColor = vec4(1.0,0.0,0.0,1.0);"+ " } ";
fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader , fragmenCode); gl.compileShader(fragmentShader); 

Program - WebGLProgram


program = gl.createProgram(); gl.attachShader(program , vertexShader ); gl.attachShader(program , fragmentShader); gl.linkProgram(program ); gl.useProgram(program);


attrixy = gl.getAttribLocation(program ,"coordinates");

gl.vertexAttribPointer(attrixy, 3, gl.FLOAT, 0, 0, false);
gl.enableVertexAttribArray(attrixy); 

gl.drawArrays(gl.POINTS, 0, 4); 

Reaction:

No comments:

No Comments

COMMENT FROM MESSAGE