[英]ThreeJS cube not showing
我正在尝试学习 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 作为我所有项目和 typescript 的最爱。 我正在尝试以正确的方式做到这一点。
相机 object 也是 3D object,默认定位在 (0,0,0)。 目前它在盒子里面。 因此你看不到盒子。 只需添加以下行应该会有所帮助(将 z 值设置为您希望相机与框的距离):
this.camera.position.set(0,0,4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.