three.js - 使用 Three.js 渲染场景

标签 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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e09488928585a0d0ced1d3d2ced2" rel="noreferrer noopener nofollow">[email protected]</a>/build/three.min.js"></script>
<canvas id="c" width="300" height="300"></canvas>

关于three.js - 使用 Three.js 渲染场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69344673/

相关文章:

javascript - Raycaster 不适用于组合相机 - 三个 js

javascript - 三个 js Canvas 纹理使用 WebGL 渲染器丢失透明度(使用 Canvasrenderer 可以)

three.js - 选择克隆的网格

three.js - 如何对 OrbitControl 施加限制?

three.js - 切平面三js后分组点

javascript - Threejs BufferGeometry - 用其他纹理渲染一些面

javascript - 将 FBO 值投影到屏幕空间以从深度纹理中读取

three.js - 在经过 CSG.js 过程后将纹理添加到 three.js 形状

Three.js 通过单击按钮更改 obj 上的 Material

javascript - Three.js 点光源阴影不在应有的位置