You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Three.js球体渲染位置异常及形状扭曲问题求助

Three.js新手问题排查:球体排列、位置偏移与扭曲问题

问题1:球体期望左右分布却前后排列

原因:你的相机位置设为(75,20,0),目标点是(0,20,0),这意味着相机沿X轴正方向放置,视线朝向X轴负方向。Three.js采用右手坐标系,默认相机视线是-Z方向,但你手动修改了相机朝向,导致原本的X轴变成了相机的前后方向,Z轴才对应左右方向。你设置球体的X坐标正负,自然会让它们沿相机的前后排列,而非左右。

解决方案:

  • 调整相机位置到Z轴方向,比如camera.position.set(0,20,75),保持目标点(0,20,0),此时X轴就是相机的左右方向;
  • 或者修改球体的Z坐标实现左右排列,比如sphere1.position.set(0,20,-20)、sphere2.position.set(0,20,20)。

问题2:球体设为(0,20,100)时向左移动

原因:还是相机朝向的问题——当相机沿X轴正方向看向原点时,Z轴正方向对应相机视角的左侧,Z轴负方向对应右侧。所以设置球体Z坐标为100,会让它出现在相机视角的左侧。

问题3:球体呈现椭圆形扭曲

原因:你没有处理窗口大小变化的事件。当窗口宽高比改变时,相机的aspect比例(宽/高)和渲染器的尺寸没有同步更新,导致透视投影矩阵变形,球体看起来被拉伸成椭圆。另外,MeshBasicMaterial不支持阴影效果,你设置的castShadow = true是无效的,可以直接去掉。

解决方案:
添加窗口resize事件监听,同步更新相机参数和渲染器尺寸:

window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

修正后的完整代码

import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

const scene = new THREE.Scene()

// 调整相机到Z轴方向,让X轴对应左右
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.set(0, 20, 75)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
controls.target.set(0, 20, 0)
controls.update()

// 球体沿X轴左右分布
const sphere1 = new THREE.Mesh(new THREE.SphereGeometry(2, 20, 20), new THREE.MeshBasicMaterial({color: 0xFFFF00}))
sphere1.position.set(-20, 20, 0);
scene.add(sphere1)

const sphere2 = new THREE.Mesh(new THREE.SphereGeometry(2, 20, 20), new THREE.MeshBasicMaterial({color: 0xFFFF00}))
sphere2.position.set(20, 20, 0);
scene.add(sphere2)

// 添加resize事件处理
window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

function animate() {
  requestAnimationFrame(animate)
  renderer.render(scene, camera)
}

animate()

内容的提问来源于stack exchange,提问作者Pravin Poudel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 00:07:09