我正在尝试将纹理应用于 nextjs 组件内部的球体。
我已经用下面的代码尝试过,但它只会显示一个黑球。
我读到这可能与纹理加载得太晚有关,但我不确定。
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 1 / 1, 0.1, 100);
camera.position.z = 20;
// lights
const aLight = new THREE.AmbientLight(0xffffff, 0.1);
const light = new THREE.DirectionalLight(0xffffff, 3);
light.position.set(-10, 5, 5);
scene.add(light);
scene.add(aLight);
const geometry = new THREE.SphereGeometry(10, 64, 64);
const texture = new THREE.TextureLoader().load("/earth_texture.jpg");
texture.colorSpace = THREE.SRGBColorSpace;
let material = new THREE.MeshPhongMaterial({
map: texture,
shininess: 100,
});
let sphere = new THREE.Mesh(geometry, material);
sphere.castShadow = true;
sphere.receiveShadow = true;
scene.add(sphere);
const renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true,
});
renderer.setSize(500, 500);
containerRef.current?.appendChild(renderer.domElement);
renderer.render(scene, camera);
嗨,
我正在尝试将纹理应用于 nextjs 组件内部的球体。
我已经用下面的代码尝试过,但它只会显示一个黑球。
我读到这可能与纹理加载得太晚有关,但我不确定。
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 1 / 1, 0.1, 100);
camera.position.z = 20;
// lights
const aLight = new THREE.AmbientLight(0xffffff, 0.1);
const light = new THREE.DirectionalLight(0xffffff, 3);
light.position.set(-10, 5, 5);
scene.add(light);
scene.add(aLight);
const geometry = new THREE.SphereGeometry(10, 64, 64);
const texture = new THREE.TextureLoader().load("/earth_texture.jpg");
texture.colorSpace = THREE.SRGBColorSpace;
let material = new THREE.MeshPhongMaterial({
map: texture,
shininess: 100,
});
let sphere = new THREE.Mesh(geometry, material);
sphere.castShadow = true;
sphere.receiveShadow = true;
scene.add(sphere);
const renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true,
});
renderer.setSize(500, 500);
containerRef.current?.appendChild(renderer.domElement);
renderer.render(scene, camera);
TextureLoader.load
是异步的。只需按照官方文档中的示例操作即可(参见TextureLoader
):
let material = new THREE.MeshPhongMaterial({
shininess: 100,
});
const loader = new THREE.TextureLoader();
loader.load(
// resource URL
"/earth_texture.jpg",
// onLoad callback
function ( texture ) {
texture.colorSpace = THREE.SRGBColorSpace;
material.map = texture;
material.needsUpdate = true;
}
);