WebGL Textures & Vertices

Beginner's Guide

Page Twenty Five

Procedural Texture-Red Blue Stripes

Stripes

This section describes how to create a texture with alternating red and blue stripes. The GLTexProcedure class defines method generateStripesRB(), to create data with red and blue vertical stripes.

The first line in every texture generation method instantiates a Uint8Array named u8a. The body of every texture generation method fills the array with color data inside a for loop. The last line in every texture generation method returns u8a.

All we need to generate stripes is to know if the for loop is processing an odd or even numbered pixel. The following line assigns either 0 or 1 to the variable j, with the modulo operator.

var j = i % 2;

If j equals zero, then the pixel represents an even entry in the array. If j equals one, then the pixel represents an odd entry in the array.

Iterate over every three entries within u8a to assign color channels. The following listing demonstrates creating a texture with alternating red and blue vertical stripes. See the entire generateStripesRB() method.

for (var i = 0; i < this.nBuffer; i = i+3){
 var j = i % 2;
 // Red stripe:
 if (j == 0){    
  u8a[i] = 255; // Red
  u8a[i+1] = 0;
  u8a[i+2] = 0; 
 }
 // Blue stripe:
 else {
  u8a[i] = 0;
  u8a[i+1] = 0;
  u8a[i+2] = 255; // Blue. 
 }    
}

Listing 22: Generate Red and Blue Stripes Procedural Data

WebGL Beginner's Guide Introduction WebGL Beginner's Guide
Copyright © 2015 Seven Thunder Software. All Rights Reserved.