带有React,3,Parcel和react-fiber-fiber的OBJLoader

时间:2019-06-12 18:41:32

标签: javascript reactjs three.js

警告不是three.js OBJLoader not loading in react的副本。不推荐使用react-three-renderer,我在这里使用功能组件。

我需要加载.obj文件,但出现两个问题。首先,它以三芯纤维的方式抛出TypeError: instance is undefined。其次,它将.obj加载为HTML:Error: THREE.OBJLoader: Unexpected line: "<!DOCTYPE html>"

这些问题与包裹,三纤维或反应三纤维有关吗?

这是无效的代码:

App.js

import React from 'react'
import { render } from 'react-dom'
import { Canvas } from 'react-three-fiber'
import Model from '/Model'
import Controls from '/Controls'
import '/style.css'

const App = () => {
  return (
    <main>
      <Canvas>
        <Model url="demo.obj" />
        <Controls />
      </Canvas>
    </main>
  )
}

render(<App />, document.getElementById('app'))

Controls.js

import React, { useRef } from 'react'
import { useThree, useRender, extend } from 'react-three-fiber'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

extend({ OrbitControls })

const Controls = props => {
  const { camera } = useThree()
    const controls = useRef()

    useRender(({ camera }) => {
        controls.current && controls.current.update()
        camera.updateMatrixWorld()
    })
  return <orbitControls ref={controls} args={[camera]} {...props} />
}

export default Controls

Model.js

import React, { useRef, useMemo } from 'react'
import { Math as THREEMath } from 'three'
import { useRender } from 'react-three-fiber'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'

const Model = ({ url }) => {
    const model = useRef()
  let rot = 0

  const obj = useMemo(() => new OBJLoader().load(url), [url])

    useRender(() => {
        const rad = 5 * Math.sin(THREEMath.degToRad(rot += 0.3))
        model.current.rotation.set(rad, rad, 0)
  })
    return <primitive object={obj} ref={model} />
}

export default Model

OBJ File here

1 个答案:

答案 0 :(得分:0)

错误的路径。 doctype的东西是它提取的404页面。从r3f 3开始,您可以使用useLoader挂钩,由于它基于反应悬念,因此使错误处理更加容易,因此您可以将其包装到错误边界和后备中。