【问题标题】:THREE is not defined; how do I fix this?三个没有定义;我该如何解决?
【发布时间】:2021-03-26 15:47:27
【问题描述】:

我目前正在尝试使用 Three.js,但似乎无法修复此错误,我尝试并搜索了很多答案,但无法修复。

我已经包含了 threejs 库 在我的脚本中,一切都写得很好

这是我的 html 索引文件

<body>
    <script src="script.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r79/three.min.js"></script>
    <script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/242637/TrackballProjectorDetector.js"></script>
    <script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/242637/AsciiEffect.js"></script>

</body> 

这是脚本文件的一部分

function init() {
      var width = window.innerWidth || 2;
      var height = window.innerHeight || 2;
      container = document.createElement('div');
      document.body.appendChild(container);
      var info = document.createElement('div');
      info.style.position = 'absolute';
      info.style.top = '20px';
      info.style.width = '100%';
      info.style.textAlign = 'center';
      info.innerHTML = 'Drag to change the view';
      container.appendChild(info);
      camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
      camera.position.y = 150;
      camera.position.z = 500;
      controls = new THREE.TrackballControls(camera);
      scene = new THREE.Scene();
      var light = new THREE.PointLight(0xffffff);
      light.position.set(500, 500, 500);
      scene.add(light);
      var light = new THREE.PointLight(0xffffff, 0.25);
      light.position.set(-500, -500, -500);
      scene.add(light);
      sphere = new THREE.Mesh(new THREE.SphereGeometry(200, 20, 10), new THREE.MeshLambertMaterial());
      scene.add(sphere);

我收到一条错误消息:

camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);

但是当我删除它时,错误会下降到下一个 THREE 元素。

【问题讨论】:

  • 我猜你是在加载three.min.js之前执行script.js。更改 &lt;script&gt; 标记的顺序,以便首先加载所有依赖项,然后将代码放在后面。另外,我建议您使用a newer version of Three.js,因为r79 大约有 3-4 年的历史。

标签: javascript three.js


【解决方案1】:
<script src="script.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r79/three.min.js"></script>

我想说这里的顺序可能很重要。如果在加载script.js(a) 时运行init 函数,则THREE 将尚未定义,因为这将发生在以下 行。

在这种情况下,解决方案是在您的脚本文件之前加载three.js


(a) 这通常在js 文件的末尾完成,但在这种情况下我们不能确定,因为我们没有整个文件。因此,我会查看该文件以查看它是否类似于:

function init() {
      blahBlahBlah();
}

init();

【讨论】:

    猜你喜欢
    • 2020-07-24
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 2021-09-04
    • 2022-07-03
    • 1970-01-01
    相关资源
    最近更新 更多