使用 three.js 渲染场景

Rendering a scene using three.js

我不知道为什么渲染器不在场景中显示球体。我是 three.js 的新手,我是否遗漏了代码中的某些内容?请告诉我。

function solar_system()
{
  const canvas = document.querySelector('c');
  const renderer = new THREE.WebGLRenderer(canvas);
  const camera = new THREE.PerspectiveCamera(70,2,0.1,1000);
  camera.lookAt(0, 0, 0);
  const scene = new THREE.Scene();
//One sphere geometry for each sphere
  const radius = 1;
  const widthSegments = 6;
  const heightSegments = 6;
  const sphereGeometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
//Making of Sun
  const sunMaterial = new THREE.MeshPhongMaterial({emissive:0xFFFF00});
  const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
  scene.add(sunMesh);
  renderer.render(scene,camera);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Solar_System</title>
    <script type="text/javascript" src = "../../../libs/three/three.js"></script>
    <script type="text/javascript" src = "../javascript/solar_system.js"></script>
    <link rel="stylesheet" href="../css/solar_system.css">
  </head>
  <body>
    <canvas id="c" width="300" height="300"></canvas>
    <script type="text/javascript">
      (function(){
        solar_system()
      })();
    </script>
  </body>
</html>

您的代码中存在一些问题:

  • 您的查询选择器有误。应该是 #c.
  • 您的相机位于原点,因此位于球体网格“内部”。
  • WebGLRenderer 的构造函数不期望 canvas 而是 parameters 对象。

请尝试一下:

const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({
  canvas
});
const camera = new THREE.PerspectiveCamera(70, 1, 0.1, 1000);
camera.position.set(0, 0, 10);
const scene = new THREE.Scene();
//One sphere geometry for each sphere
const radius = 1;
const widthSegments = 6;
const heightSegments = 6;
const sphereGeometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
//Making of Sun
const sunMaterial = new THREE.MeshPhongMaterial({
  emissive: 0xFFFF00
});
const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
scene.add(sunMesh);
renderer.render(scene, camera);
body {
    margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<canvas id="c" width="300" height="300"></canvas>