Wrogrsin
Wrogrsin

Reputation: 105

Making a cube with images as sides in Three.js

I have tried quite a bit of stuff but have not found anything online. When I run my program I get this error: XMLHttpRequest cannot load file:///C:/Users/winst/Documents/Programming%20Projects/Miner/textures/Dirt.jpg. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

The file is a simple picture I made that looks kinda like dirt.

Here is the part of my code that is doing it:

// load texture
var textureLoader = new THREE.TextureLoader();

var texture0 = textureLoader.load( 'textures/Dirt.jpg' );
var texture1 = textureLoader.load( 'textures/Dirt.jpg' );
var texture2 = textureLoader.load( 'textures/Dirt.jpg' );
var texture3 = textureLoader.load( 'textures/Dirt.jpg' );
var texture4 = textureLoader.load( 'textures/Dirt.jpg' );
var texture5 = textureLoader.load( 'textures/Dirt.jpg' );

var materials = [
    new THREE.MeshBasicMaterial( { map: texture0 } ),
    new THREE.MeshBasicMaterial( { map: texture1 } ),
    new THREE.MeshBasicMaterial( { map: texture2 } ),
    new THREE.MeshBasicMaterial( { map: texture3 } ),
    new THREE.MeshBasicMaterial( { map: texture4 } ),
    new THREE.MeshBasicMaterial( { map: texture5 } )
    ];
var material = new THREE.MeshFaceMaterial( materials );

// Combine everything together
var mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { material } ));

The rest of the code ran perfectly well with simply doing colored cubes instead of images on the sides. I found most the code above from another Stack Overflow question but mine still dosen't work.

Please help me. :)

Upvotes: 0

Views: 2287

Answers (1)

Alex Under
Alex Under

Reputation: 1489

You are facing CORS problem when requesting local textures. It two words - your code is trying to request files that can't be served to your program because of security issues.

As @prisoner849 has mentioned - you should start by reading this article. It will give you basic idea of how to work with files in your local THREE.js script.

Answering your primary question, here is an example of how you can apply different textures for each cube side:

var cubeMaterials = [
    new THREE.MeshBasicMaterial({map: image1}),
    new THREE.MeshBasicMaterial({map: image2}),
    new THREE.MeshBasicMaterial({map: image3}),
    new THREE.MeshBasicMaterial({map: image4}),
    new THREE.MeshBasicMaterial({map: image5}),
    new THREE.MeshBasicMaterial({map: image6}),
  ];
  cubeMaterials = new THREE.MeshFaceMaterial( cubeMaterials );

  var cubeGeometry = new THREE.BoxGeometry(100,100,100);
  var cube = new THREE.Mesh(cubeGeometry,cubeMaterials);

You can find working example here

Upvotes: 0

Related Questions