WebGL Textures & Vertices

Beginner's Guide

Page Twenty Eight

Procedural Texture-Red Green Random Colors

Random Colors

This section describes how to create a texture with random values for red and green color channels. The GLTexProcedure class defines method generateRandomRG(), to create data with random values for red and green.

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.

The for loop within generateRandomRG() calls the JavaScript method Math.random() which returns a value between 0.0 and 1.0. Multiply the random number by 255 to obtain a value between 0.0 and 255.0. Values might exist to the right of the decimal point. A Uint8Array only holds whole number integers. In other words entries in Uint8Array can't include floating point numbers. Assignment to an entry in the Uint8Array truncates values after the decimal point. See the entire generateRandomRG() method.

for (var i = 0; i < this.nBuffer; i = i+3){ 
 // Red:
 u8a[i] = Math.random()*255;  
 // Green:
 u8a[i + 1] = Math.random()*255; 
 // Blue:
 u8a[i + 2] = 0; 
}

Listing 24: Generate Random Colors Procedural Data

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