d_z90
d_z90

Reputation: 1263

Three.js - Set texture for background scene FAILED

I am trying to create an animation in three.js with two scenes running at the same time. The first one has a fixed texture, which works as the background for the page, while the second one has a rotating cube. This is the part of the code where I am getting the issue:

THREE.ImageUtils.crossOrigin = '';
var texture = THREE.ImageUtils.loadTexture('https://i.imgur.com/eoWNz.jpg');
var backgroundMesh = new THREE.Mesh( 
    new THREE.PlaneGeometry(2, 2, 0),
    new THREE.MeshBasicMaterial({
         map: texture
    }));

I tried to follow this example and this question to solve the issue with the security concerning cross-origin images by using a simple http server with python, but still the background remains black.

Do you by any chance have an idea of what am I doing wrong? This is the fiddle with the complete code.

Thanks in advance for your replies!

EDIT:

Locally I get this error: THREE.Material: 'map' parameter is undefined. in three.min.js:428

Upvotes: 1

Views: 4340

Answers (2)

Wilt
Wilt

Reputation: 44326

To set a static background for your canvas you can simply set background-image in css for your body or your container. It is important to set your renderer to transparent for this to work (otherwise the background of the renderer is covering your background image). To do this set the renderer alpha to true:

// Create renderer and set alpha to true
renderer = new THREE.WebGLRenderer({
    alpha: true
});

And then the following css will do the job:

div#container {
  position: relative;
  height: 100%;
  width: 100%;
  background-image: url("https://i.imgur.com/eoWNz.jpg");

  /* some additional styling to center it nicely */
  background-repeat: no-repeat;
  background-position: center;
  position: fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover !important;
}

Demonstrated here in this fiddle.

Upvotes: 1

Wilt
Wilt

Reputation: 44326

There were several issues that I ran into. Most importantly you used this url for the image:

https://i.sstatic.net/HEJtH.jpg

But that link points to a web page.
The actual image is located on this url:

https://i.sstatic.net/V1527.jpg

To allow cross origin you have to set the crossOrigin property on the loader to true:

var loader = new THREE.TextureLoader();
loader.crossOrigin = true;

And you had two scenes I am not sure why, I removed one.

Here a working fiddle with the end result.

Upvotes: 1

Related Questions