Having trouble loading texture locally in THREE.js?

Here's the scenario: I have a local file where I attempt to load a texture using the following code:

var texture = THREE.ImageUtils.loadTexture( 'image.jpg' );
var cubeGeo = new THREE.CubeGeometry( 50, 50, 50 );
var cubeMat = new THREE.MeshBasicMaterial( { map: texture } );
var cube = new THREE.Mesh( cubeGeo, cubeMat );
scene.add( cube );

However, when I try to run this code on my computer, the image does not appear (the cube remains black). Strangely, when I move the entire folder to a server and access it from there, the image is displayed as expected.

My question is, why does the code work when the files are hosted on a server but not when they are stored locally on my computer? All necessary files have been copied over properly. I even tried using an absolute path but still no luck. Is there a specific setting that needs to be adjusted on my computer for this to work? I am currently running Windows 7 with Chrome version 32.0.1700.76 m and using THREE.js r64 without any additional libraries or plugins.

Answer №1

The issue you are experiencing is a result of security restrictions that need to be addressed.

To resolve this problem, it is recommended to run a local server.

For detailed information on how to set up and run things locally with three.js, visit the wiki article at How to Run Things Locally.

Using version r.112 of three.js

Answer №2

If you are looking to incorporate textures into your project, a useful method is to convert images into base64 strings and then assign them directly to your variables.

Take a look at this example: https://codepen.io/tamlyn/pen/RNrQVq

var texture = new THREE.Texture();
texture.image = image;
image.onload = function() {
texture.needsUpdate = true;
};

The 'image' variable in the code snippet above is extracted from the base64 string.

You have the option to create a res.js file and store all your textures there :) This approach may not be ideal as it requires re-conversion of images to base64 when changes are made, but it is compatible with any browser, including Microsoft Edge.

Answer №3

If you're feeling lost on this topic (I definitely was at first), one way to clarify things is by setting up a local server. I personally used node - http://nodejs.org/download/ to get node).

Once you have that sorted, navigate to your project directory and enter the following command in the terminal:

npm install http-server -g

To start the server, simply type:

http-server

You can then access your project through the default local page

http://localhost:8080/

You should now be able to view your project there.

Answer №4

Seems like I'm fashionably late to the gathering, as usual.

Surprisingly, you can achieve this without the need for setting up a node server, unless, of course, you require a backend for other reasons.

The trick is to load your local image into the browser by converting it into a Base64 string using the FileReader object.

Once you have converted the image to a Base64 string, you have the option to either save it to sessionStorage (which is limited to around ~4 Mb on average) or keep the string stored in a variable while your "app" is active.

You can then transform the base64 string into a three.js texture and apply it to an object within your scene. It's important to note the asynchronous render call in the example below; The scene must be rendered once the texture has fully loaded, or else it won't be displayed properly.

In the following example, I am loading the three.texture using my image that has been uploaded to sessionStorage.

TEXTURE = THREE.ImageUtils.loadTexture(
      sessionStorage.getItem('myBase64Img');
      {},
      function () { renderScene(); /* async call after texture is loaded */ }
    );

Cheers!

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

ngAnimateSwap - animations do not function as intended when boolean expressions are utilized

I adapted the original ngAnimateSwap demonstration from the AngularJS documentation to utilize a boolean expression for triggering the slide animation. Initially, I anticipated the banner to switch back and forth between 'true' and 'false&a ...

Maintaining DOM modifications once a link has been clicked and the Back button is pressed

Is there a way in JavaScript to prevent appended items from disappearing when the user clicks another link and then presses the Back button after using jQuery's appendTo() method to add items to an unordered list? ...

Working with an undefined object in jQuery

Currently, I am delving into the realm of creating MVC5 web pages utilizing JQuery and Ajax. As part of an exercise, I developed the following function: <script language="javascript"> $.get("GetCustomersByJson", null, BindData); function Bi ...

Is it possible for me to create a nested component without having to make a new file

What I desire: Home.vue <template> <div> <p>{{message}}</p> <ChildComponent/> </div> </template> <script setup> import { ref, defineComponent } from 'vue'; let message = r ...

Trouble with the datepicker

I tried using the datepicker from and followed its demo, but unfortunately, the datepicker is not showing up on my page. I have gone through everything carefully, but I am unable to identify the reason behind this issue. Could someone please assist me i ...

"Composing perfect sentences: The art of incorporating quotes

I am attempting to include text with quotes in a DIV, like so: "All is well that ends well" The text is generated dynamically and I'm using a JavaScript font replacement plugin (CUFON) to add quotes around the text. Sometimes, the ending quote drops ...

Deploying scripts after CloudFormation deployment

After each deployment on AWS, I have a specific npm script called db:migrate that I need to run. This script is responsible for executing the migrate.js file, which handles all database migrations. Currently, my deployments are managed using AWS CloudForm ...

Using jQuery to create a Select All Checkbox that toggles a specific class

I have come across similar examples in the past, but I have been unable to make it work as intended. The examples I found only use standard checkboxes. I attempted to customize the checkbox using a sprite sheet by applying a class, but I am struggling to a ...

Encountering error when using require() with Firebase in Express

I am facing an issue with my Express application while attempting to connect it to Firebase. Currently, my console is showing an error message: C:\Users\Tyler\Desktop\Dev\food-bank\app.cjs:19 const firebase = initializeApp(fi ...

Update the sum upon deleting a feature in an HTML and JavaScript form

Once a row or field is added, this function will display a delete link. When clicked, it will remove the row or field: var ct = 1; function addNewRow(){ ct++; var divElement = document.createElement('div'); divElement.id = ct; // Code to cr ...

After being redirected from another page using history() in React, the state is initially set to null but later gets updated to the correct value - Firebase integration

After logging in and being redirected to the profile page, I encounter an error that says 'Unhandled Rejection (TypeError): Cannot read property 'email' of null'. How can I ensure that the state is set before proceeding with any additio ...

What could be the reason for ng-init failing to activate the $watch listener?

When I run the code in my application, there are instances where ng-init fails to trigger the $watch function. Any suggestions on how to fix this? HTML <div ng-controller="MyCtrl"> <p ng-init="stages = 'coco'">{{x}}</p> < ...

Exploring the behavior of Object.assign in for loops and forEach loops

I've come across an interesting anomaly with Object.assign in the following scenario. function sampleFunction(index, myList) { myList.forEach((element, i) => { if (i === index) { console.log(Object.assign({}, {"newKey": " ...

Utilizing jQuery to manage asynchronous tasks, such as executing AJAX requests, handling promises, and using deferred

Exploring My jQuery Plugins: (function ($, window, document, undefined) { $.fn.loadPageContent = function (url, dataToSend) { url = url || window.location.href; dataToSend = dataToSend ? dataToSend : {}; return $.post(url, data ...

The font family specified in the Materia UI theme is experiencing compatibility issues on browsers that are not Chrome

Having difficulty overriding some elements with a specific font, as it seems to work perfectly on Chrome but not on other browsers like Safari and FireFox. Could there be something overlooked? Below is the code snippet: const customTheme = createMuiTheme( ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

Ways to resolve the issue of my sidebar displaying at the bottom of the page on smaller screens

Below is the code snippet that generates a Bootstrap page with lorem text and a sidebar. The issue I am facing is that when the browser window size gets smaller, the sidebar appears at the bottom instead of the side. On very small resolutions, it becomes h ...

What is the best way to locate the closest element using JavaScript?

Is there a way to locate the closest object to the mouse pointer on a webpage? I have a hypothesis that involves utilizing the array function, however, I am uncertain if that is the correct approach. Furthermore, I lack knowledge of which specific proper ...

Tips for achieving a blurred background image effect when hovering, while keeping the text unaffected

Hey there, I've recently started my journey into web development and have encountered a roadblock. I'm trying to blur the background image of a div on hover without affecting the text inside. I have an id called c1 where I used a javascript func ...

Using Vue.js to invoke an external JavaScript function for search functionality

In my vue.js application, I have a list of users with backend pagination. Now I want to implement a search functionality. I attempted to call the method like this: watch: { search: function() { Crud.methods.getItems(); } }, Howe ...