使用带有 three.js 的 A 帧会影响 three.js?

Using A-frame with three.js will affect three.js?

我发现我的项目使用 A-frame 和 three.js 会触发以下错误:

Uncaught TypeError: THREE.CSS3DObject is not a constructor

我用这个样本来测试:

https://threejs.org/examples/#css3d_periodictable

它的源代码:

https://github.com/mrdoob/three.js/blob/master/examples/css3d_periodictable.html

当我将 A 帧脚本添加到此示例时,它触发了相同的错误。

<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/libs/tween.min.js"></script>
<script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
<script src="https://threejs.org/examples/js/renderers/CSS3DRenderer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.7.1/aframe.js"></script>

A 帧会影响 three.js 吗?它们可以一起使用吗? 如何使这个示例工作(停止显示错误)?

谢谢!

这是因为aframe捆绑了three.js所以全局变量window.THREE在aframe.js中被重新定义了。原来的 three.js,加载了 TrackballControls 和 CSSRenderer,在加载 aframe.js.

后无法再访问

你可以看到,如果你这样做的话:

<script src="https://threejs.org/build/three.js">
</script>
<script src="https://threejs.org/examples/js/libs/tween.min.js"></script>
<script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
<script src="https://threejs.org/examples/js/renderers/CSS3DRenderer.js"></script>
<script>
  window._THREE = THREE;
  delete window.THREE;
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.7.1/aframe.js"></script>

<script>
  console.log(_THREE.REVISION, THREE.REVISION);
</script>

因此,更改顺序(而不是再次加载 three.js)应该对您有所帮助:

<script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.7.1/aframe.js"></script>
<script src="https://threejs.org/examples/js/libs/tween.min.js"></script>
<script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
<script src="https://threejs.org/examples/js/renderers/CSS3DRenderer.js"></script>

但是,您应该知道 aframe 使用的是不同的 three.js 版本,这可能会导致与示例页面中的最新版本发生冲突。

另一个需要注意的相关事项是 aframe 不能与 css3d-renderer 一起工作,因为 DOM-elements 不能在 WebVR 中显示。