Gianmarco6000
Gianmarco6000

Reputation: 37

Three.js Texture loading

I am starting during this days with Three.js and it's very cool. Now i would like to load a texture and apply it to a simple sphere. My problem is that when i open the browser page i get this error. I don't know how to solve this problem.

Code

window.onload = Init;

var scene;
var camera;
var renderer;


function render() {
   renderer.render(scene, camera);
   requestAnimationFrame(render);
}




function Init() {
   scene = new THREE.Scene();
   camera = new THREE.PerspectiveCamera(75, window.innerWidth /window.innerHeight, 0.1, 1000);
   renderer = new THREE.WebGLRenderer();



  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor(0xeeeeee, 1);

  camera.position.set(15, 13, 12);
  camera.lookAt(scene.position);

  var cubeGeometry = new THREE.SphereGeometry(5, 30, 30);




  var loader = new THREE.TextureLoader();
  loader.load("texture/earth.jpg", function(texture) {
      var material = new THREE.MeshLambertMaterial({ map: texture });
      var sphere = new THREE.SphereGeometry(5, 30, 30);
      var mesh = new THREE.Mesh(sphere, material);
      scene.add(mesh);
  });
  var light = new THREE.SpotLight(0xffffff);
  light.position.set(10, 20, 20);
  scene.add(light);


  document.body.appendChild(renderer.domElement);

  render();
}

Upvotes: 1

Views: 509

Answers (1)

Lloyd MacLea
Lloyd MacLea

Reputation: 61

Three.js is attempting to load the image from the filesystem, as evidenced by the file:// URL in your screenshot. This is prohibited by default in modern browsers, though there are a couple ways around it:

  • (Recommended) Run your code from a local HTTP server. If you have Python installed, run python -m SimpleHTTPServer from the directory of your project to spin up a simple server.
  • (Not recommended) Launch a web browser with local file access enabled (e.g. --allow-file-access-from-files in Chromium). This is highly insecure, do not surf around in a browser with with this setting active.

Upvotes: 1

Related Questions