我正在尝试学习 ThreeJS,所以我将该库添加到现有的 NextjS 项目中。我想在我的首页看到一个立方体。但我什么也看不见。渲染器代码是:
import React from 'react';
import * as THREE from 'three';
type Props = { initialize: Function };
export default class Renderer extends React.Component<Props, {}> {
canvas !: HTMLCanvasElement;
renderer !: THREE.WebGLRenderer;
GLcontext !: WebGLRenderingContext;
constructor(props: any) { super(props); }
componentDidMount() {
this.canvas = document.getElementById('default-canvas') as HTMLCanvasElement;
this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true });
this.GLcontext = this.renderer.getContext();
this.renderer.setClearColor ('#000000');
this.renderer.setSize (window.innerWidth, window.innerHeight);
this.props.initialize (this.renderer);
window.addEventListener ('resize', () => {
this.renderer.setSize(window.innerWidth, window.innerHeight); });
}
render() {
return(
<div>
<canvas id="default-canvas" className="canvas-style" />
</div>
);
}
}
场景代码是:
import React from 'react';
import * as THREE from 'three';
import Renderer from './renderer';
export default class Scene extends React.Component {
scene !: THREE.Scene;
camera !: THREE.Camera;
constructor(props: any) { super(props);
this.initialize = this.initialize.bind(this);
}
initialize (renderer: THREE.WebGLRenderer) {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const geometry = new THREE.BoxGeometry(1, 1, 1);
const m = new THREE.MeshStandardMaterial({ color: 0xb300b3 });
var cd = new THREE.Mesh(geometry, m)
this.scene.add(cd);
cd.position.x = 0;
cd.position.y = 0;
cd.position.z = 0;
var ambientLight = new THREE.AmbientLight( 0x666666, 1.0 );
this.scene.add( ambientLight );
// Create a white directional light with an intensity of 1.0
var directionalLight = new THREE.DirectionalLight( 0xffffff, 1.0 );
directionalLight.position.set( 0, 10, 0 );
this.scene.add( directionalLight );
renderer.render(this.scene, this.camera);
}
render() {
return(
<div>
<Renderer initialize={this.initialize} />
</div>
);
}
}
似乎没有任何效果,我看到的只是空荡荡的场景。我将 NextJS 用作我所有项目和打字稿的最爱。我正在尝试以正确的方式做到这一点。