Three.js 由于纹理加载而呈现黑色场景。
我在 Angular 组件(Angular 版本 8)中使用 Three.js。
我试图遵循 rendering Earth in WebGL 上的旧 Three.js 教程它使用现已弃用的 THREE.ImageUtils.loadTexture()
来加载网格 Material 贴图的纹理。
它对我不起作用,所以我尝试使用现代的THREE.TextureLoader().load()
。然而,由于某种原因,它从未对其回调采取行动。
所以我尝试将 THREE.TextureLoader().load()
与 THREE.LoadingManager()
搭配使用。虽然 THREE.LoadingManager()
的回调似乎有效,但它仍然只产生带有一些光线的黑色场景。
虽然我是使用 Three.js 的新手, 对我来说,我的代码似乎是:
- 包含灯光
- 似乎不仅仅渲染一次
- 不会向控制台抛出任何错误
代码:
在我的 component.html 中:
...
<div #rendererContainer></div>
...
在我的 component.ts 中:
import {Component, OnInit, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
import * as THREE from 'three';
export class MyComponent implements OnInit, AfterViewInit {
@ViewChild('rendererContainer', {static: false}) rendererContainer: ElementRef;
renderer = new THREE.WebGLRenderer();
scene = null;
camera = null;
mesh = null;
earthSurface = new THREE.MeshStandardMaterial({color: 0xaaaaaa});
constructor() {
// scene and camera
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 1000);
this.camera.position.z = 1.5;
// light
this.scene.add(new THREE.AmbientLight(0x333333));
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 3, 5);
this.scene.add(light);
const manager = new THREE.LoadingManager();
const textureLoader = new THREE.TextureLoader(manager);
this.earthSurface.map = textureLoader.load('planet.jpg');
manager.onLoad = () => {
// call back
const geometry = new THREE.SphereGeometry(0.5, 32, 32);
this.mesh = new THREE.Mesh(
geometry,
this.earthSurface
);
this.scene.add(this.mesh);
this.rerender();
console.log(this.earthSurface);
};
}
ngOnInit() {}
ngAfterViewInit() {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.rendererContainer.nativeElement.appendChild(this.renderer.domElement);
this.animate();
// setInterval(() => {this.rerender();}, 1.5 * 1000);
}
rerender() {
this.renderer.render(this.scene, this.camera);
}
animate() {
this.renderer.render(this.scene, this.camera);
window.requestAnimationFrame(() => this.animate());
}
}
最佳答案
我进行了测试,您的代码可以使用一些建议
您可以完全放弃重新渲染功能,只需确保加载场景的颜色,如下所示:
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xf5f5f5);
确保您加载的图像具有正确的路径,您可以尝试:
this.earthSurface.map = textureLoader.load('https://upload.wikimedia.org/wikipedia/commons/b/b8/Exploding_planet.jpg');
关于angular - Three.js + Angular : texture loading fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58906753/