Guide on how to import image data instead of an image using THREE.js in javascript

I wrote a JavaScript function that loads an image as a texture:

var loader = new THREE.TextureLoader();
loader.load( 'textures/canvas1.png', function ( texture ) {
    var geometry = new THREE.SphereGeometry( 200, 20, 20 );
    var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
    var mesh = new THREE.Mesh( geometry, material );
    group.add( mesh );
} );

This function works perfectly fine. But now, I want to load a dynamically created image map instead. This image map is generated through the following code snippet:

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var image = context.createImageData(map_width, map_height);
var data = image.data;               
var scale = 5.18;
for (var x = 0; x < map_width; x++) {                  
    for (var y = 0; y < map_height; y++) {
        var nx = x/map_width-0.5;
        var ny = y/map_height-0.5;                    
        var value = Math.abs(noise.perlin2(scale*nx, scale * ny));
        value *= 256;

        var cell = (x + y * map_width) * 4;                    
        data[cell] = data[cell + 1] = data[cell + 2] = Math.pow(1.2, value);                              
        data[cell + 3] = 255; // alpha.                                    
    }
}

I attempted to use the below piece of code (including creating a Uint8Array based on the suggestions in the comments), but all I see is a completely black sphere:

var buffer = new ArrayBuffer(data.length);
var udata = new Uint8Array(buffer);
for (var i=0; i<data.length; i++) {
    udata[i] = data[i];     
}

var geometry = new THREE.SphereGeometry( 200, 20, 20 );
var texture = new THREE.DataTexture(udata, map_width, map_height, THREE.RGBAFormat );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
var mesh = new THREE.Mesh( geometry, material );
group.add( mesh );

I wonder if the data needs to be provided in a different format?

Answer №1

To create a DataTexture and use it as the map for your material, follow this pattern:

Create a new array called data with 4 times the size
// Populate and initialize the data...

Create a new DataTexture using the data, width, height, and RGBAFormat
Set the type of the texture to UnsignedByteType

Create a new MeshBasicMaterial with the map property set to the texture
Create a new Mesh using the geometry and material

Add the mesh to the scene

Version: three.js r.128

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

Issue with Node.js: Promise not completing execution

My current project involves retrieving data from multiple collections in MongoDB using Node.js and promises. Below is a snippet of the basic code I am using: await Promise.all( ["a", "b", "c"].map(async (collection) =& ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

Tips for saving images that are loaded indirectly on websites

Is there a way to save images that are loaded using methods other than being embedded directly in web pages or stored in a temp folder or browser cache? You can check out the situation I am referring to here. Any tips on saving images from the gallery on ...

Sending data to an Express server in Node.js using JavaScript

My current project involves the use of javascript, html, nodejs, express, and mysql to fetch values from a database and send them back to the html interface. In this setup, the user inputs a domain in the 'btnSearch' textbox and clicks on the Lo ...

An easy guide to animating multiple sections of progress bars individually in Bootstrap

My Bootstrap code successfully animates a section of progress bars when the user views it. However, it currently animates all progress bars on the page rather than just those in the viewed section. This means that when the user moves to another section, th ...

Using Node.js: Differentiating between two forms on the server side

I am currently working on a project that involves having two forms on my HTML page: <form id="enterForm" action="/" enctype="multipart/form-data" method="post"> <fieldset> <textarea id="queries" name="queries"></textarea&g ...

Can the text color be customized to match the brightness level of the background area being covered?

Does anyone know of a plugin or method that can automatically change the color of text or swap predefined images/icons based on the average brightness of its parent element's background? If the background is dark, it should make the text white or swit ...

What is the process of enabling scrolling on the main panel once scrolling on the sidebar has concluded?

How can I achieve a scrolling behavior similar to the one demonstrated here? When scrolling through the sidebar, I want it to continue scrolling until it reaches the end. After that, any further scrolling on the sidebar should scroll the main panel inste ...

What is the best way to omit the final item in a v-for loop?

I'm just starting out with JavaScript and learning about JS frameworks. I recently came across this snippet of Vuejs code: <div v-for="coefficient in coefficients" class="coefficient"> <div> <span class="name">name:{{coe ...

Updating Variables in Azure DevOps Code Prior to DeploymentORModifying Variables

Can Azure DevOps automate code updates upon release? For instance, in my React app, I have a setting file with export const ISPROD = false. I want Azure DevOps to modify this value to true before building and deploying the app. Is this achievable? Please ...

Replace particular letters within the text with designated spans

Suppose I have this specific HTML code snippet: <div class="answers"> He<b>y</b> <span class='doesntmatter'>eve</span>ryone </div> Additionally, imagine I possess the subsequent array: ['correct' ...

When invoking a function within another function, it is essential to ensure that both values are returned within the function

When calling a function within another function function1(){ return this.a } function2(){ return this.b } To output in string format, you can call function1 inside function2 function2(){ var resultOfFunction1 = this.function1(); return resultOfFunction1 ...

Spacing placeholder

Is there a way to leave the placeholder text in place while typing and have it extend forward as I type? For example, if I type 100 spaces and then "INX", it should look like this: 100 INX So that as I type "100." the "INX" moves forward, resulting in: ...

ThreeJS - Module displaying surface texture in a visual environment devoid of illumination

When it comes to rendering my scene, I work with intricate objects that boast a complex surface structure. Interestingly, I have made the deliberate choice to steer clear of using light within my scene. Currently, I rely on the MeshNormalMaterial to accura ...

Attempting to nest an AJAX request within the success callback of another AJAX request

I am attempting to execute two jQuery ajax calls, with the second call being made from the success callback of the first. I have experimented with different variations of the code, such as adjusting the brackets. Below is my attempted code snippet: $.aja ...

Trick to enable editing in Bootstrap Select Combobox

Is there a way for users to add their own options to bootstrap-select? Greetings! I have spent some time searching for a straightforward solution that is compatible with Bootstrap 4 styling. Despite exploring various suggestions, as well as unresolved thr ...

obtain information from a Java servlet on a web page

I am working on a webpage that displays various coordinates (longitude, latitude), and I need to create a Java class to sort these coordinates. My plan is to send the coordinates to a Java servlet before displaying them on the webpage. The servlet will th ...

What is the best way to include an attribute to an object in a knockout observable array and ensure a notification is triggered?

Implementing Knockout.js in my project, I have an observable array included in the view model. function MyViewModel() { var self = this; this.getMoreInfo = function(thing){ var updatedThing = jQuery.extend(true, {}, thing); ...

What steps do you take to establish a relay connection for pagination in an ORM framework?

After thorough research of Relay's documentation, I have yet to find a clear explanation on how to establish a Relay connection with an ORM. The examples provided mainly utilize the connectionFromArray method, which works well for data stored in memor ...

When utilizing bootstrap, encasing an input text element in a label results in the text becoming bold and not occupying the entire width

I have been experimenting with wrapping my text input fields in labels. While this technique works well with pickers on my form, it seems to cause issues when applied to text boxes. If I choose not to wrap the text boxes, the alignment between the label an ...