DEV Community

Melvin Debot
Melvin Debot

Posted on

I can't import my obj file in Three Js

the error
Alt Text
Html

<input type="file" id="importMesh" accept=".obj">
Enter fullscreen mode Exit fullscreen mode

Javascript

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
const mouse = new THREE.Vector2();
let raycaster = new THREE.Raycaster();
let arrayObject = [];
let canvas = document.getElementById('canvas')

let renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setClearColor(0xe5e5e5);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);


camera.position.z = 250;

let controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.campingFactor = 0.25;
controls.enableZoom = true;

let keyLight = new THREE.DirectionalLight(
  new THREE.Color("hsl(70,100%,75%)"),
  1.0
);
keyLight.position.set(-100, 0, 100);

let fillLight = new THREE.DirectionalLight(
  new THREE.Color("hsl(240, 100%, 75%)"),
  0.75
);
fillLight.position.set(100, 0, 100);

let backLight = new THREE.DirectionalLight(0xffffff, 1.4);
backLight.position.set(100, 50, -100); 

scene.add(keyLight);
scene.add(fillLight);
scene.add(backLight);


let input = document.getElementById("importMesh");
input.addEventListener("change", function(event) {
  var file = this.files[0];
  console.log('file',file)
  var reader = new FileReader();
  reader.addEventListener("load", function (event) {
    var contents = event.target.result;
    let loader = new THREE.OBJLoader();
    let geometry = loader.parse(contents);
    console.log("load object", geometry);
    var material = new THREE.MeshStandardMaterial({
      vertexColors: true,
      color: 0xec0404,
      overdraw: 0.5,
    });

    var mesh = new THREE.Mesh(geometry, material);

    mesh.castShadow = true;
    mesh.receiveShadow = true;

    scene.add(mesh);
  }, false);
  if (reader.readAsBinaryString !== undefined) {
    reader.readAsBinaryString(file);
  } else {
    reader.readAsArrayBuffer(file);
  }
});

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

animate();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)