WebGL Textures and Vertices eBook Screen Shots

Read Pixel Colors Tutorial

Read Pixel Colors from Procedural Texture Example Introduction Source Code Summary

Introduction

This very short tutorial includes some source code explaining how to read pixels with WebGL.

Select procedural textures from a menu in the Read Pixel Colors from Procedural Texture example. Tap the canvas. WebGL method readPixels() obtains color values where you tapped. The source code below demonstrates how to use readPixels().

Source Code

The following source code demonstrates how to use the WebGL readPixels() method with the Read Pixel Colors from Procedural Texture example.

// Create an array
// to hold four
// eight bit values.
var colors = new Uint8Array(
 4
);

// Render beforehand
// places the scene
// in the buffer.
glDemo.render(
 controller
);

// Read just
// one pixel
// at the X coordinate 'nX'
// and Y coordinate 'nY'
// on the canvas.
// Stores values into 'colors'
// parameter.
gl.readPixels(
 nX,
 nY, 
 1,
 1, 
 gl.RGBA, 
 gl.UNSIGNED_BYTE, 
 colors
); 

// Red is the
// first Byte.
var nR = colors[0];

// Green is the
// second Byte.
var nG = colors[1];

// Blue is the
// third Byte.
var nB = colors[2];

// The fourth Byte
// contains the alpha
// channel. 
var nA = colors[3];
 
// HTML Element
// for display
// to the user.
var eDebug = document.getElementById(
 'eDebug'
);
 
// Display values for
// each color channel:
eDebug.innerHTML = "Red:"+nR+", Green: "+nG+", Blue:"+nB+", Alpha: "+nA;

Summary

This very short tutorial includes some source code explaining how to read pixels with WebGL.

Select procedural textures from a menu in the Read Pixel Colors from Procedural Texture example. Tap the canvas. WebGL method readPixels() obtains color values where you tapped. The source code above demonstrates how to use readPixels().

Learn to create simple procedural textures with the e-book WebGL Textures & Vertices: Beginner's Guide from Amazon.

WebGL Games E-Book Screen Shots
Copyright © 2015 Seven Thunder Software. All Rights Reserved.