Loading textures locally using three.js is functioning properly, however, remote loading is not functioning as

I have customized an official example for the Loader object to showcase a specific issue. My goal is to generate a mesh with a texture map that loads before creating the geometry. Currently, I am facing a problem where local files load properly, but remote ones do not. You can observe this behavior in action:

  • working demo (local):
  • not working demo (remote): nylkiway.net/loadertest_remote.html

When using the loader to load a locally saved .jpg, the texture appears correctly on the final mesh, as demonstrated in the working demo:

    <!DOCTYPE html>
<html lang="en">
<head>
  <title>three.js webgl - loaders - OBJ loader</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
  <div id="info">
    <a href="http://threejs.org" target="_blank">three.js</a> - image loader test
  </div>

  <script src="libs/three.min.js"></script>

  <script>

  var container;

  var camera, scene, renderer;

  var mouseX = 0, mouseY = 0;

  var windowHalfX = window.innerWidth / 2;
  var windowHalfY = window.innerHeight / 2;


  init();
  animate();


  function init() {

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
    camera.position.z = 100;

    // scene

    scene = new THREE.Scene();

    var ambient = new THREE.AmbientLight( 0x101030 );
    scene.add( ambient );

    var directionalLight = new THREE.DirectionalLight( 0xffeedd );
    directionalLight.position.set( 0, 0, 1 );
    scene.add( directionalLight );

    // texture
    var manager = new THREE.LoadingManager();
    var texture = new THREE.Texture();

    var loader = new THREE.ImageLoader( manager );
    loader.load( 'avatar.jpg', function ( image ) {

    // uncomment next line and comment above to see the issue!

    //loader.load( 'http://nylkiway.net/avatar.jpg', function (image) {

      texture.image = image;
      console.log("debug. image size: " + image.width + " X " + image.height);
      texture.needsUpdate = true;

    });

    // model
      var object = new THREE.Mesh(new THREE.BoxGeometry(100, 100, 100), new THREE.MeshBasicMaterial({map: texture}));
      object.position.y = -80;
      scene.add(object);

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    document.addEventListener('mousemove', onDocumentMouseMove, false);

  }

  function onDocumentMouseMove(event) {
    mouseX = (event.clientX - windowHalfX) / 2;
    mouseY = (event.clientY - windowHalfY) / 2;
  }


  function animate() {
    requestAnimationFrame(animate);
    render();
  }

  function render() {
    camera.position.x += (mouseX - camera.position.x) * .05;
    camera.position.y += (-mouseY - camera.position.y) * .05;
    camera.lookAt(scene.position);
    renderer.render(scene, camera);
  }

</script>
</body>
</html>

However, when attempting to load the same image from a remote server, the texture appears to load, or at least it seems to because I can access the image's width and height in the onLoad() callback. Despite this, I encounter errors and the mesh does not render. Uncommenting the following line:

loader.load( 'http://nylkiway.net/avatar.jpg', function (image) {

Results in multiple errors:

"THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. (undefined)"

Even though the image is identical, my debug output reflects the dimensions of the image:

console.log("debug. image size: " + image.width + " X " + image.height);

"debug. image size: 460 X 460"

I do not believe this to be a CORS issue since the completed image loading callback is triggered. The properties of the images are also readable. I sense that this could be a common query, but my search did not yield a suitable answer. I don't think the issue lies in the dimensions of the images not being powers of 2, given that the locally loaded image displays correctly as a texture.

Any assistance would be greatly appreciated!

Answer №1

There seems to be a CORS issue with your demo due to warnings:

Uncaught SecurityError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at http://i.imgur.com/Gps8L9R.jpg may not be loaded.

To resolve this, consider hosting your own image mirror and directing it there using a 'reverse proxy':

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

Utilizing a custom out variable instead of relying on gl_FragColor in shaders

In my quest to create a simple shader for coloring a cube using Three.js with WebGL as the shader language, I encountered a problem. Here's an image of the cube in question Initially, I used gl_FragColor in my FragmentShader and it worked fine. Howe ...

What are the best strategies for enhancing the performance of the jQuery tag:contains() selector

My goal is to extract all elements from a webpage that contain a specific set of words. For example, if I have an array of random words: words = ["sky", "element", "dry", "smooth", "java", "running", "illness", "lake", "soothing", "cardio", "gymnastic"] ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

Modifying Data in Another Component in VueJS

I have a classic Vue Component structured like the following: Vue.component('bar', { template: `<div class="bar"></div>`, data () { return { blocks: [ ] ...

react component not displaying image

I must admit, this might be a silly question but I'm just starting out in web development. My goal is to create a clickable image component that redirects to another page on the website. However, despite not encountering any errors, the image is not ...

Add unique styles to a jQuery-included HTML document

I'm attempting to use jQuery to load an HTML page into the main body of another page. Specifically, I have a div called sidebar_menu positioned in the middle of the page, and I am loading content at the bottom using jQuery. $("#sidebar_menu").load(" ...

What is the purpose of having a constructor in Typescript when an interface is already used for a class?

Is it necessary to have a constructor in my class if the class already implements an interface? It seems like redundant code to me. interface PersonInterface { firstname: string; lastname: string; email: string; } class Person implements Pe ...

What is the best way to manage the retrieved data in a situation where I am utilizing async-await along with the useEffect hook?

I need to retrieve a player's statistics based on the input provided by the user, and then show it. I am facing challenges in storing the retrieved data using the useEffect hook. Any suggestions for a more efficient approach? import React, { useEf ...

Trouble with CSS animation when incorporating JavaScript variables from a PHP array

Whenever I use a script to fetch an array of objects from PHP... I successfully display the results on my website by outputting them into Divs. The challenge arises when I introduce CSS animations. The animation only triggers if the variable length excee ...

Importing vs Referencing Videos in Next.js - What is the Best Practice for Video Integration in Next.js?

I'm looking to use a video as a background in my banner design. Typically, with images in Next.js, I would import them and then pass the import as src (for example: import img from '@images/about-us-page/img.svg'). However, when attempting ...

Using Typescript: Defining a function parameter that can be either of two interfaces

While browsing through this specific question, I noticed that it was somewhat related to my current issue, although there were notable differences. In my scenario, I have a function named parseScanResults which accepts an object as its argument. This obje ...

Issues with implementing Rails 4 with jQuery, javascript, and coffee scripts causing functionality to malfunction

Although I have nearly two decades of experience in C/C++ for control systems and firmware, as well as proficiency in shell and perl scripting, I am new to rails and web development. Despite including jquery in the application.js manifest, I am unable to ...

List component in Angular not refreshing after sorting the array in the service

Currently, I am delving into the realm of Angular (version 5+) to enhance my skills by working on a small project. The project involves setting up basic routing functionalities to showcase the ContactList component upon selecting a navigation tab. Addition ...

Issue with border spacing functionality

I'm having some difficulty with my border spacing in CSS. No matter what size I specify, it doesn't seem to have any effect. I just want to use a border for the top line. Here is my CSS: p { border-spacing: 5000px; text-align: right; ...

Sorting the array in MongoDB before slicing it

Currently, I have a pipeline that aggregates Regions along with their respective countries and sales values. My goal is to obtain the top 5 countries by sales in each region using the $slice method. However, the issue I am facing is that it returns the fir ...

Is there a way to change the color of the menu button to white if the points are not visible?

I have created CSS to style the menu's color and make the buttons change color based on different actions. However, I also want the buttons to match the colors of the points on the map. To achieve this, I set the background color in JavaScript when ge ...

The ability to submit a conversation chat is currently

I encountered an issue when attempting to submit a chat, and I received the error message 'handlebar is not define'. I followed the code tutorial provided in this link: https://codepen.io/drehimself/pen/KdXwxR This is the screenshot of the error ...

Step-by-step guide to implementing a user-friendly search input field using the powerful AngularJS material design framework

I am searching for an effortless method to implement a feature similar to the expandable search text field in angular-mdl. By clicking on a search button, it will expand into a text field. <!-- Expandable Textfield --> <form action="#"> < ...

What is the preferred method for logging out: using window.location.replace('/') or setting window.location.href to window.location.origin?

When it comes to a logout button, which is the better option: window.location.replace('/') or window.location.href=window.location.origin? Can you explain the difference between these two methods? It's my understanding that both of them remo ...

Why does Googlebot need to retrieve HTML from JSON-exclusive URLs?

Link to a page like this: The following code is found: $.getJSON("/newsfeeds/61?order=activity&amp;type=discussion", function(response) { $(".discussion-post-stream").replaceWith($(response.newsfeed_html)); $(".stream-posts").before($("<div cl ...