Skip to main content

Using shaders to apply color in WebGL

Having created a square plane in the previous demonstration, the next obvious step is to add a splash of color to it. We can do this by revising the shaders.

Applying color to the vertices

In WebGL, objects are built using sets of vertices, each of which has a position and a color; by default, all other pixels' colors (and all its other attributes, including position) are computed using interpolation, automatically creating smooth gradients. Previously, our vertex shader didn't apply any specific colors to the vertices; between this and the fragment shader assigning the fixed color of white to each pixel, the entire square was rendered as solid white.

Let's say we want to render a gradient in which each corner of the square is a different color: red, blue, green, and white. The first thing to do is to establish these colors for the four vertices. To do this, we first need to create an array of vertex colors, then store it into a WebGL buffer; we'll do that by adding the following code to our initBuffers() function:

initBuffers(){
  const colors = [
    1.0,  1.0,  1.0,  1.0,    // white
    1.0,  0.0,  0.0,  1.0,    // red
    0.0,  1.0,  0.0,  1.0,    // green
    0.0,  0.0,  1.0,  1.0,    // blue
  ];

  const colorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);

  return {
    position: positionBuffer,
    color: colorBuffer,
  };
}

This code starts by creating a JavaScript array containing four 4-value vectors, one for each vertices' color. Then a new WebGL buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer.

To make these colors actually get used, the vertex shader needs to be updated to pull the appropriate color from the color buffer:

  const vsSource = `
    attribute vec4 aVertexPosition;
    attribute vec4 aVertexColor;

    uniform mat4 uModelViewMatrix;
    uniform mat4 uProjectionMatrix;

    varying lowp vec4 vColor;

    void main(void) {
      gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
      vColor = aVertexColor;
    }
  `;

The key difference here is that for each vertex, we pass its color using a varying to the fragment shader.

Coloring the fragments

As a refresher, here's what our fragment shader looked like previously:

  const fsSource = `
    void main() {
      gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }
  `;

In order to pick up the interpolated color for each pixel, we need to change this to fetch the value from the vColor varying:

  const fsSource = `
    varying lowp vec4 vColor;

    void main(void) {
      gl_FragColor = vColor;
    }
  `;

Each fragment receives the interpolated color based on its position relative to the vertex positions instead of a fixed value.

Drawing using the colors

Next, it's necessary to add the code look up the attribute location for the colors and setup that attribute for the shader program:

  const programInfo = {
    program: shaderProgram,
    attribLocations: {
      vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
      vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'),
    },
    ...

Then, drawScene() can be revised to actually use these colors when drawing the square:


// Tell WebGL how to pull out the colors from the color buffer // into the vertexColor attribute. { const numComponents = 4; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color); gl.vertexAttribPointer( programInfo.attribLocations.vertexColor, numComponents, type, normalize, stride, offset); gl.enableVertexAttribArray( programInfo.attribLocations.vertexColor); }

Comments

Popular posts from this blog

Upload image 4

WebGL: 2D and 3D graphics for the web

WebGL (Web Graphics Library) is a JavaScript API for rendering high-performance interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 <canvas> elements. This conformance makes it possible for the API to take advantage of hardware graphics acceleration provided by the user's device. Support for WebGL is present in Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+, Internet Explorer 11+, and Microsoft Edge build 10240+; however, the user's device must also have hardware that supports these features. The WebGL 2 API introduces support for much of the OpenGL ES 3.0 feature set; it's provided through the WebGL2RenderingContext interface. The <canvas> element is also used by the Canvas API to do 2D graphics on web pages.

Test iOS

This is a test from iOS simulator.  Bold text  Italic text Underline   Strikethrough Text color Text background color Header 1 Header 2 Header 3 Header 4 Header 5 Header 6  Paragraph Quote text  Text size  Text font  Align left Align center Align right Align justify Indent 1 Indent 2 Superscript Subscript This a link to google Horizontal line 1 2 3 1 2 3