Using ThreeJS to Load a Texture from an ArrayBuffer in JavaScript

If I have a JavaScript ArrayBuffer containing binary image data along with the image extension (such as jpg, png, etc), I want to create a ThreeJS Texture without the need for an HTTP request or file load as I already have the binary information.

For example, let's say I have:

var binaryData = getBinaryData(); // This function returns an ArrayBuffer with the image data, assuming it's a PNG image for this example.
var imageFormat = "png";

(As well as other texture properties like wrap mode, mipmaps, etc)

How can I go about loading the Texture in this scenario?

Any assistance on this matter would be greatly appreciated.

Answer №1

To utilize your array of binary data effectively, you can convert it into a base64 string. Once converted, you can then attach it to an Image object and proceed to use the Image object with a Three.js Texture.

// Converting the array of data into a base64 string
var stringData = String.fromCharCode.apply(null, new Uint16Array(jpgData));
var encodedData = window.btoa(stringData);
var dataURI = "data:image/jpeg;base64," + encodedData;

// Linking the image to the Texture
var texture = new THREE.Texture();

var image = new Image();
image.onload = function () {
    texture.image = image;
    texture.needsUpdate = true;
};
image.src = dataURI;

Provided below is the complete code snippet (the low-resolution cat image is deliberately used):

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var jpgData = new Uint8Array([255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,254,0,62,67,82,69,65,84,79,82,58,32,103,100,45,106,112,101,103,32,118,49,46,48,32,40,117,115,105,110,103,32,73,74,71,32,74,80,69,71,32,118,54,50,41,44,32...skipped for brevity..."]);
// The remaining code is skipped for brevity
<html>
<head>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.min.js"></script>
</body>
</html>

Answer №2

I have been exploring methods to directly load an arraybuffer to a texture. Presently, we are resorting to creating a local URL as a workaround, using the following code snippet.

const blob = new Blob([arraybuffer]);
let url =  window.URL.createObjectURL(blob);

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

Tips for accessing the value of the range slider in Bootstrap 5 while it is being slid

Is it possible to capture the value from a Bootstrap 5 slider while sliding? I want to continuously receive the value as I move the handle, rather than only getting the final value when I release the handle. Currently, I am using a Bootstrap 5 range slide ...

Tips for choosing elements in JavaScript using querySelector even after they've been included in the code using innerHTML

Within the scenario below, a parent element is present in the HTML code and the span element with a class of 'child' is nested within the parent element using the createChild function. Subsequently, the content of the child element is modified el ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Experiencing an issue with Handsontable: Every time I try to run the countRows method, all I get is "undefined."

Greetings everyone! I appreciate you taking the time to read about my issue. I've been using the handsontable library for a week now and have encountered some difficulties with certain methods. Within a function, I have the following code: count = $ ...

Tips on implementing a Javascript function triggered by a user's click within the video player frame

<script> function greet() { alert("hello"); } </script> <iframe width="100%" height="315" src="https://www.youtube.com/embed/AGM0ibP1MRc" onclick="greet()"></iframe> .Kindly assist me, please. ...

Creating a Form Layout with Bootstrap - Organizing Text Boxes and Text Areas

https://i.sstatic.net/oqRwR.jpg In the image above, I need to adjust the position of the textbox to align it with the TextArea. Is there a Bootstrap class that can help me achieve this? My current version of Bootstrap is 3.3.6. HTML &l ...

How can I use jQuery to locate all elements that match a specific style within the DOM?

Similar Question: How can I target hidden elements? Selecting multiple elements with CSS display:none property <div class="container"> <p style="display:none">I am hidden</p> <p>I am visible</p> <p>I am also ...

Struggling to successfully submit data from an API to the project's endpoint, encountering Error 405 method rejection

I'm working on integrating data from the openweathermap API into my project's endpoint to update the User interface. Everything seems to be functioning correctly, except for when I attempt to post the data to the endpoint. What am I overlooking h ...

Using JQUERY to handle event bubbling in the DOM after an AJAX call

I have been attempting to dynamically append content to a specific div using .ajax() and then utilize the new content within a jQuery Dialog. I believe that my usage of .on() is correct, but it appears that the DOM is not being properly updated. Here is t ...

Using MEAN.JS to Define Query Parameters for Mongo from the Client Controller

I am currently developing an application using the MEAN stack - MongoDB, Angular, Express, and Node.js. To kickstart my project, I utilized the MEAN.JS generator to set up the initial structure of my application. The articles module within my application ...

Leveraging the power of Auth0 and Prisma in aggregating user data

In my current project, I am developing a Next.js application with Auth0 as the authentication system. Users are authenticated using the standard middleware: import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge'; export default wi ...

The battle between Iteration and Recursion: Determining the position of a point in a sequence based

One of the challenges I'm facing involves a recursive function that takes a point labeled {x,y} and then calculates the next point in the sequence, recursively. The function in question has the following structure: var DECAY = 0.75; var LENGTH = 150 ...

Retrieve JSON information using AJAX

As I am new to JSON and Ajax, the question I have may seem basic. When I try to display data from my JSON object containing 'name', 'task', 'date', and 'status' using Ajax, it does not show up on my page. Below is m ...

Leveraging Flask to pass data to Google Charts with JavaScript

Trying to integrate Google Charts on my website using Flask as the backend. Need help with sending data from Flask to JavaScript. Here's a snippet of where I plan to retrieve data later: @app.route("/") def home(): data = {'Language': &a ...

Building a solid foundation for your project with Node.js and RESTful

I need to integrate a legacy system that offers an api with rest/json queries in Delphi. I plan to consume this data and build an app using angular + nodejs. My goal is for my application (client) to only communicate with my web-server on nodejs, which wil ...

Tips for creating nested child routes in AngularJS 2 with ID:

Here is a Demo of what I'm working on. Just getting started with angularjs 2 and trying to figure things out. I want to display Twitter names that correspond to certain names using routes on the same page, specifically utilizing a second <router- ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...

how to use jQuery to locate the immediately preceding node that meets specific criteria

How can I locate the nearest parent node above $(this) node that has a specific property such as class="field", without considering parent/child relationships? ...

Error occurred during npm build with Browserify: Module not found

When I run npm build with the following command: "build": "browserify -t [ babelify --presets [ es2015 react ] ] app/assets/app.jsx -o public/javascripts/app.js" I encounter the error message below: Error: Cannot find module 'components/maininput.j ...

Are web components capable of managing changes in CSS (maybe through cssChangedCallback)?

Is there a way to control the application of CSS to a web component similar to using attributes through attributeChangedCallback. I am currently developing a couple of web components that could benefit from being styled with CSS classes. However, I requir ...