25 Sept 2020

Which is better Threejs or WebGL?


If you are  the person who coding graphic animation  program. Then you have  come  lots of difficulty and  situation when you got failed to retrieve results as you aspect throughout  your  program.
If you  come to my Blog. You are  on your right way or places. I hope you deeply interested in graphics programming.

In this particular post I am going  to give a brief helpful answer. That Which is better threejs oe webgl for web graphics stuff. 

In one word I will say threejs. Because  threejs is javascript library for Webgl.  This wraps actually lengthy codes into javascript function, object and constructor with  meaningful name.

WebGL vs Threejs

Here i am actually going to show you that how lengthy codes become with WebGL or Three Js.


WebGL is low level JavaScript API which is based on OpenGL 2.0.  Generally Low Level API or Programming language are closely to Assembly language.
To create a single point in WebGL you have to go through all of point I have given as bullets. Let's  follow them to understand it.

  • Creating vertex buffer object (VBO) and see how data binding is done.
      var buffer = gl.createBuffer();
      gl.bindBuffer( gl.ARRAY_BUFFER , buffer );
      gl.bindData( gl.ARRAY_BUFFER , new Float32Array([0.0, 0.0]), gl.STATIC_DRAW);
  • Creating shaders of type Vertex shader & Fragment Shader and passing these shader to gl.
    attribute vec2 coordinate; void main(){ gl_Position = vec4(coordinate, 1.0, 1.0); gl_PointSize = 10.0; }
      var vertexShader = gl.createShader(gl.VERTEX_SHADER);
       gl.shaderSource(vertexShader , vertexCode);
    Note* - again you have to write Fragment Shader. Same as above vertexShader.
  • Creating program and passing both of shader and linking them to gl.
        var program = gl.createProgram();
        gl.attachShader(program  , vertexShader );
        gl.attachShader(program , fragmentShader);
        gl.linkProgram(program );
  • Retrieving attributes location, pointing vertex attribute and enable the vertex attribute arrays.
        attrixy =  gl.getAttribLocation(program ,"coordinate");
       gl.vertexAttribPointer(attrixy, 3, gl.FLOAT, 0, 0, false);
  • Final blow. calling drawArrays .
        gl.drawArrays(gl.POINTS, 0, 1);


Now let's see magic with threejs. 

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera(60, 412/604 , 1, 2000 );
camera.position.set(0, 0, 30);

var renderer = new THREE.WebGLRenderer(); renderer.setSize(412, 604); 

document.body.appendChild(renderer .domElement); 

var geometry = new THREE.Geometry(); geometry.vertices.push(new THREE.Vector3(.0,.0,.0)); 

var point = new THREE.Points( geometry ); scene.add(point ) 

var light = new THREE.AmbientLight(); scene .add(light ); 

//draw call
renderer.render(scene , camera ); 


No comments:

No Comments