简体   繁体   中英

How can I import .obj file in reactjs using typescript?

I am making react project with typescript. There is need to import.obj file, so I imported threejs library and react-three-fiber library like following;

import React, { useState, useMemo } from 'react'
import logo from './logo.svg';
import { Canvas } from 'react-three-fiber';
import { Group } from 'three';
import './App.css';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';

Next, I have got no idea what, I am just beginner for using typescript in react. I am using react 17.0.3, function component operation. Who can teach me.obj file import code? Help me.

You can use three-obj-loader package:

  1. import OBJLoader from "three-obj-loader"
  2. const objLoader = new THREE.OBJLoader()
  3. objLoader.load('asset.obj', callback)

Here is an example: https://codesandbox.io/s/kw7l49nw1r?file=/src/ThreeScene.js:7034-7048

ThreeJS has build in loaders three "^0.128.0" You can

import { ObjectLoader, MaterialLoader} from 'three';

    const objLoader = new ObjectLoader()
    objLoader.load(
      "./assets/test.obj", 
      obj => {
         // On Load
      },
      event => {
         // On Progress
      },
      err => {
         // On Error
      }
    )
)

This is the code snippet I used in a react application created with CRA.

import {
  MeshBasicMaterial,
  Mesh,
  DoubleSide,
  Vector3,
  TextureLoader,
  AdditiveBlending,
  PlaneGeometry,
  Matrix4,
  ObjectLoader,
} from 'three';

const createPin = ({ x, y, z }) => {
  const objLoader = new ObjectLoader()
  const pinObj = objLoader.parse(require('./ball-head-pin-scene.json'))

  const vector = new Vector3(x, y, z)
  const axis = new Vector3(0.1, 0, 1)
  pinObj.quaternion.setFromUnitVectors(axis, vector.clone().normalize())

  return pinObj
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM