I am trying to load a glTF
file in my reactjs
application using gltf
loader. I manage to display a basic cube on the canvas, but using the gltf
loader I only get the blank canvas without the 3D object.
I have tried several paths to the file but it seems to sit in the correct position (same folder as component). I have also tried other glTF
files without luck. Do i need to include the bin file somewhere?
Here is my code:
import React, { Component } from 'react';
import * as THREE from 'three';
import GLTFLoader from 'three-gltf-loader';
const OrbitControls = require("three-orbit-controls") (THREE);
class Viewer extends Component{
componentDidMount(){
const width = this.mount.clientWidth
const height = this.mount.clientHeight
//ADD SCENE
this.scene = new THREE.Scene()
//ADD CAMERA
this.camera = new THREE.PerspectiveCamera(
75,
width / height,
0.1,
1000
)
this.camera.position.z = 4
//ADD RENDERER
this.renderer = new THREE.WebGLRenderer({ antialias: true })
this.renderer.setClearColor('#888888')
this.renderer.setSize(width, height)
this.mount.appendChild(this.renderer.domElement)
//ADD ORBIT CONTROL
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
//ADD CUBE
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: '#433F81' })
this.cube = new THREE.Mesh(geometry, material)
this.scene.add(this.cube)
//ADD OBJECT
const loader = new GLTFLoader();
loader.load('model.gltf', (object) => {
this.scene.add(object.scene);
});
this.animate();
}
componentWillUnmount(){
this.stop()
this.mount.removeChild(this.renderer.domElement)
}
animate = () => {
this.renderScene()
this.frameId = window.requestAnimationFrame(this.animate)
}
renderScene = () => {
this.renderer.render(this.scene, this.camera)
}
render(){
return(
<div
style={{ width: '400px', height: '400px' }}
ref={(mount) => { this.mount = mount }}
/>
)
}
}
export default Viewer;
The application should show the 3D file on the canvas.
NOTE: I'm new to three.js, so layman terms would be appreciated.
You can turn gltf files to JSX and use react-three-fiber to reconcile threejs. Here's an example: https://github.com/react-spring/react-three-fiber/tree/3.x/tools three-fiber wraps threejs similar to how react-dom wraps html, reconcilers don't necessarily change the rules, which makes it less of an abstraction as it seems.
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.