The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application?

const gl = renderer.context;
const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
// read image data from gl
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, currentFrame);

Here is the code snippet for the Threejs application:

const renderer = new THREE.WebGLRenderer({preserveDrawingBuffer: true});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight );

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 6;

const geometry = new THREE.BoxGeometry(10, 10, 10);
const cube = new THREE.Mesh(geometry);
scene.add(cube);

The RGB values are returning correctly, but I am facing an issue with the alpha value always being set to 255.

Answer №1

There are two potential scenarios to consider.
One possibility is that the internal buffer contains a value of 1.0 (255) for the alpha channel in all texels.
Alternatively, it could be that the buffer you are reading from does not have an alpha channel at all, meaning the internal format is likely RGB.

The WebGL 1.0 Specifications - 5.13.12 Reading back pixels makes reference to the OpenGL ES 2.0 Specification.

Referencing the OpenGL ES 2.0 Specification - 3.6.2 Transfer of Pixel Rectangles:

Final Expansion to RGBA

Each group is converted to a group of 4 elements as follows: If a group lacks an A element, then A is added and set to 1.0. If R, G, or B is missing from the group, each absent element is added and given a value of 0.0.


It is important to note that if you do not specify the alpha channel for the vertex attribute used in fragment color writing, the default alpha channel will be 1.0 (255 in RGBA8 buffer), as all vertex attributes initialize with (0, 0, 0, 1):

The WebGL 1.0 Specifications - 5.13.10 Uniforms and attributes also points towards the OpenGL ES 2.0 Specification.

Check out OpenGL ES 2.0 Specification - See 2.7 Current Vertex State:

The state required to support vertex specification includes MAX_VERTEX_ATTRIBS four-component floating-point vectors to store generic vertex attributes. The initial values for all generic vertex attributes are (0, 0, 0, 1).


If you intend to add an alpha channel to a geometry within a THREE.mesh, you must use a transparent material on the mesh with an opacity lower than 1.0. View THREE.material:

var geometry = new THREE.BoxGeometry( 10, 10, 10 );  
var material = new THREE.MeshBasicMaterial( {
    color: 0xff0000,
    transparent: true, 
    opacity: 0.5,
} );
const cube = new THREE.Mesh(geometry, material);


To read an alpha channel successfully, ensure that the canvas has an alpha (transparency) buffer by setting the alpha attribute of the THREE.WebGLRenderer:

renderer = new THREE.WebGLRenderer( {
    alpha: true
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to undo the click event in Javascript?

Is there a way to revert back to the initial position after clicking? I successfully changed the x icon to a + icon on click, but now I'm struggling to reverse that action. I've tried using MOUSEUP and DBLCLICK events, but they aren't ideal ...

Using Mongoose schema with a reference to an undefined 'ObjectID' data type

I am currently working on establishing relationships between my schemas, and I have encountered some issues with my solution. Here is how my device schema looks like: var deviceSchema = schema({ name : String, type : String, room: {type: mongo ...

Is there a way to identify when a fresh google instant page appears?

I am currently developing a browser extension that requires making a call when a new Google instant page is loaded and then modifying the results, similar to SEOQuake. One problem I encountered is that if a user pastes a link directly into the URL field a ...

Implement a loader in AngularJS to display when transitioning between pages

Is there a way to implement a loader that appears when the page starts changing and only disappears once the entire page is fully rendered to prevent clipping bugs? I have already set up the loader as shown below: $scope.$on('$routeChangeStart' ...

Issue with margins of sections when attempting to activate menu class while scrolling

My Objective: I want to create a website where the menu highlights the section that is currently being viewed as the user scrolls up and down. Progress So Far: I have successfully implemented a functioning menu that changes to "active" when the correspo ...

Arranging data structures in JavaScript: Associative arrays

I'm facing a major issue. My task is to organize an array structured like this: '0' ... '0' ... 'id' => "XXXXX" 'from' ... 'name' => "XXXX" ...

Finding and merging duplicate values within a Javascript array

I am working with a dynamically generated array that looks like this: var myArray = ("0% { left:74px; top:202px; }" , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" ); Within the array, there are 2 entries that ha ...

Issue with relative templateUrl in Angular 2 not resolving paths

As I embark on creating my first Angular 2 app, I'm faced with the task of setting my template in an HTML file using `templateUrl`. Currently, both the component.ts and view.html are stored in the same folder under src/ directory. Here's what I ...

Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;? However, if I use bracket notation like return contacts[i][prop];, it works fine an ...

Create a new modal design by keeping the structure but updating the text and images for

Is there a way to simplify the process of creating multiple modals on my website without having to duplicate and adjust the code each time? I would appreciate any assistance in achieving this! I have a specific modal template that I want to replicate, wit ...

Exploring ElectronJs: The journey to sending messages from ipcMain to IpcRender and awaiting a response

I need help with sending a message to ask the renderer to parse an HTML string mainWindow.webContents.send('parse html', { resp}) The renderer processes the data and sends a reply ipc.on('parse html',function(e,p){ let b ...

Add rows to the table dynamically and then execute the script

My table dynamically creates rows when a button is clicked, and there is an input box with an auto suggest script. The auto complete works fine on the default first box, but not on the dynamically added row. How can I make the auto complete script work o ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

Accessing elements within documents opened using the window.open method

My goal is to open a new browser window based on a provided URL using JavaScript's window.open function. However, my ultimate aim is to inspect the newly opened window and alter its URL to redirect to a different site. I attempted to achieve this with ...

why is the sum coming out as an undefined number?

My challenge involves creating a table that should display the total price, however, it keeps showing NaN. The code snippet below outlines how the total price is calculated: import React from 'react'; const Total = (props) => { const {ite ...

Executing jQuery code after a data update in Angular can be achieved by utilizing

Currently, I am working with Angular 1.4.7 on a site that was not set up by me. As a result, I am uncertain about the specific information needed in this scenario. We are displaying search filters, but their enabling or disabling is controlled by data fetc ...

Is there a way to execute "npm run dev" within cPanel while I am currently working on a Laravel project?

Currently, I am working on a Laravel project and require to execute the following command in Cpanel terminal: npm run dev https://i.sstatic.net/bzxNj.png ...

Gatsby MDX fails to locate the desired page despite displaying the title and slug

Currently diving into the world of Gatsby and I've decided to implement MDX for my blog pages. Following a helpful tutorial here on programmatically creating pages. All seems well as I can view them in my GraphQL and displaying the list of articles i ...

Divide the strings within an array

When working with nodejs, I utilize walksync to obtain an array as shown below: var paths = ['Essential Classes.jade' , 'introduction.jade'] These are the filenames contained within a folder. The objective is to extract only the filen ...

Exploring the process of implementing smooth transitions when toggling between light and dark modes using JavaScript

var container = document.querySelector(".container") var light2 = document.getElementById("light"); var dark2 = document.getElementById("dark"); light2.addEventListener('click', lightMode); function lightMode(){ contai ...