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().

A number of initialization details were left out, to focus on the main topic. Most WebGL projects initialize as described in the WebGL e-book series. However information in this tutorial should apply to other WebGL projects, such as those that use Unity or three.js, as well.

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().

Tags

learn to code, Web GL, 3D Programming, 3D Development, 3D Media, 3D Web, 3 D Websites, 3D Development, 3D Web Design, 3D Web Development, Web Development, free tutorials, online learning, learn coding, create 3D website, 3D Media, JavaScript, html5, html 5, Web GL, 3D rendering software, GLSL, 3D Graphics Engine, 3D rendering software, html tutorial, how to code, programming websites, learn computer programming, learn to code for free, learning coding, stem, 3D images, webgl simple example, webgl basics,
Learn 3D Programming Learn 3D Programming
Copyright © 2015 Seven Thunder Software. All Rights Reserved.