WebGL - 顏色



在我們之前的所有示例中,我們透過為gl_FragColor變數分配所需的顏色值來為物件應用顏色。除此之外,我們還可以為每個頂點定義顏色 - 就像頂點座標和索引一樣。本章以一個示例演示如何使用 WebGL 為四邊形應用顏色。

應用顏色

要應用顏色,您必須使用 JavaScript 陣列中的 RGB 值為每個頂點定義顏色。您可以為所有頂點分配相同的值,以使物件具有唯一的顏色。定義顏色後,您必須建立一個顏色緩衝區並將這些值儲存在其中,並將其與頂點著色器屬性關聯。

在頂點著色器中,除了儲存頂點位置的座標屬性外,我們還定義了一個attribute和一個varying來處理顏色。

color屬性儲存每個頂點的顏色值,varying是作為片段著色器輸入傳遞的變數。因此,我們必須將color值賦值給varying

在片段著色器中,儲存顏色值的varying被賦值給gl_FragColor,後者儲存物件的最終顏色。

應用顏色的步驟

建立 WebGL 應用程式以繪製四邊形併為其應用顏色需要以下步驟。

步驟 1 - 準備 Canvas 並獲取 WebGL 渲染上下文

在此步驟中,我們使用getContext()獲取 WebGL 渲染上下文物件。

步驟 2 - 定義幾何體並將其儲存在緩衝區物件中

可以使用兩個三角形繪製正方形。因此,在此示例中,我們提供了兩個三角形(共用一條邊)的頂點和索引。由於我們希望為其應用顏色,因此還定義了一個儲存顏色值的變數,並將每個(紅色、藍色、綠色和粉色)的顏色值分配給它。

var vertices = [
   -0.5,0.5,0.0,
   -0.5,-0.5,0.0, 
   0.5,-0.5,0.0,
   0.5,0.5,0.0 
];

var colors = [ 0,0,1, 1,0,0, 0,1,0, 1,0,1,];
indices = [3,2,1,3,1,0]; 

步驟 3 - 建立和編譯著色器程式

在此步驟中,您需要編寫頂點著色器和片段著色器程式,編譯它們,並透過連結這兩個程式建立一個組合程式。

  • 頂點著色器 - 在程式的頂點著色器中,我們定義向量屬性以儲存 3D 座標(位置)和每個頂點的顏色。宣告一個varing變數以將顏色值從頂點著色器傳遞到片段著色器。最後,將儲存在顏色屬性中的值分配給varying

var vertCode = 'attribute vec3 coordinates;'+
   'attribute vec3 color;'+
   'varying vec3 vColor;'+
	
   'void main(void) {' +
      ' gl_Position = vec4(coordinates, 1.0);' +
      'vColor = color;'+
   '}';
  • 片段著色器 - 在片段著色器中,我們將varying分配給gl_FragColor變數。

var fragCode = 'precision mediump float;'+
   'varying vec3 vColor;'+
   'void main(void) {'+
      'gl_FragColor = vec4(vColor, 1.);'+
   '}';

步驟 4 - 將著色器程式與緩衝區物件關聯

在此步驟中,我們將緩衝區物件和著色器程式關聯起來。

步驟 5 - 繪製所需的物件

由於我們使用索引繪製兩個將構成四邊形的三角形,因此我們將使用drawElements()方法。對於此方法,我們必須傳遞索引的數量。indices.length的值指示索引的數量。

gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);

示例 - 應用顏色

以下程式演示瞭如何使用 WebGL 應用程式繪製四邊形併為其應用顏色。

<!doctype html>
<html>
   <body>
    <canvas width = "300" height = "300" id = "my_Canvas"></canvas>

      <script>
         /*============= Creating a canvas ==================*/
         var canvas = document.getElementById('my_Canvas');
         gl = canvas.getContext('experimental-webgl');
         
         /*========== Defining and storing the geometry ==========*/

         var vertices = [
            -0.5,0.5,0.0,
            -0.5,-0.5,0.0,
            0.5,-0.5,0.0,
            0.5,0.5,0.0
         ];

         var colors = [0,0,1, 1,0,0, 0,1,0, 1,0,1,];
         
         indices = [3,2,1,3,1,0];
         
         // Create an empty buffer object and store vertex data
         var vertex_buffer = gl.createBuffer();
         gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
         gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
         gl.bindBuffer(gl.ARRAY_BUFFER, null);

         // Create an empty buffer object and store Index data
         var Index_Buffer = gl.createBuffer();
         gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
         gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
         gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

         // Create an empty buffer object and store color data
         var color_buffer = gl.createBuffer ();
         gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
         gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);

         /*======================= Shaders =======================*/
         
         // vertex shader source code
         var vertCode = 'attribute vec3 coordinates;'+
            'attribute vec3 color;'+
            'varying vec3 vColor;'+
            'void main(void) {' +
               ' gl_Position = vec4(coordinates, 1.0);' +
               'vColor = color;'+
            '}';
            
         // Create a vertex shader object
         var vertShader = gl.createShader(gl.VERTEX_SHADER);

         // Attach vertex shader source code
         gl.shaderSource(vertShader, vertCode);

         // Compile the vertex shader
         gl.compileShader(vertShader);


         // fragment shader source code
         var fragCode = 'precision mediump float;'+
            'varying vec3 vColor;'+
            'void main(void) {'+
               'gl_FragColor = vec4(vColor, 1.);'+
            '}';
            
         // Create fragment shader object
         var fragShader = gl.createShader(gl.FRAGMENT_SHADER);

         // Attach fragment shader source code
         gl.shaderSource(fragShader, fragCode);

         // Compile the fragmentt shader
         gl.compileShader(fragShader);

         // Create a shader program object to
         // store the combined shader program
         var shaderProgram = gl.createProgram();

         // Attach a vertex shader
         gl.attachShader(shaderProgram, vertShader);

         // Attach a fragment shader
         gl.attachShader(shaderProgram, fragShader);

         // Link both the programs
         gl.linkProgram(shaderProgram);

         // Use the combined shader program object
         gl.useProgram(shaderProgram);

         /* ======== Associating shaders to buffer objects =======*/

         // Bind vertex buffer object
         gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);

         // Bind index buffer object
         gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);

         // Get the attribute location
         var coord = gl.getAttribLocation(shaderProgram, "coordinates");

         // point an attribute to the currently bound VBO
         gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);

         // Enable the attribute
         gl.enableVertexAttribArray(coord);

         // bind the color buffer
         gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
         
         // get the attribute location
         var color = gl.getAttribLocation(shaderProgram, "color");
 
         // point attribute to the volor buffer object
         gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ;
 
         // enable the color attribute
         gl.enableVertexAttribArray(color);

         /*============Drawing the Quad====================*/

         // Clear the canvas
         gl.clearColor(0.5, 0.5, 0.5, 0.9);

         // Enable the depth test
         gl.enable(gl.DEPTH_TEST);

         // Clear the color buffer bit
         gl.clear(gl.COLOR_BUFFER_BIT);

         // Set the view port
         gl.viewport(0,0,canvas.width,canvas.height);

         //Draw the triangle
         gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
      </script>
   </body>
</html>

如果執行此示例,它將產生以下輸出 -

廣告