在多个div上渲染多个场景

时间:2018-08-07 13:02:27

标签: javascript three.js 3d render

我使用了map函数来创建多个场景。在该map函数中,我创建了一定数量的div(该数量取决于场景)。如何将每个场景附加到每个div

当我尝试渲染时,第一个模型(或除最后一个模型以外的所有其余模型)闪烁显示,然后消失,然后显示最后一个模型。据我了解,这与渲染功能有关。

但是我不知道现在该怎么办。任何帮助,将不胜感激。

  let cameraInstance = new THREE.PerspectiveCamera(
          75,
          window.innerWidth / window.innerHeight,
          0.1,
          1000
        )
        const rendererInstance = new THREE.WebGLRenderer({ alpha: true })
        rendererInstance.setSize(300, 200)
        const oControl = new OrbitControls(
          cameraInstance,
          rendererInstance.domElement
        )

        const loaderInstance = new THREE.JSONLoader()

        let createSceneInstance = tempInstances.map((tempInstance, i) => {
          let sceneInstance = new THREE.Scene()
          const ambientLight = new THREE.AmbientLight(0x383838)
          sceneInstance.add(ambientLight)

          const spotLight = new THREE.SpotLight(0xffffff)
          spotLight.position.set(300, 300, 300)
          spotLight.intensity = 1
          sceneInstance.add(spotLight)

          let newDiv = document.createElement('div')
          newDiv.id = 'instance' + i
          document.getElementById('instances').appendChild(newDiv)

          loaderInstance.load(
            path + tempInstance.json3d,
            // eslint-disable-next-line
            (geo, mat) => {
              let ins1 = new THREE.Mesh(geo, mat)
              ins1.scale.set(20, 20, 20)
              sceneInstance.add(ins1)

              cameraInstance.position.set(30, 35, 40)
              cameraInstance.lookAt(sceneInstance.position)

              const render = () => {
                requestAnimationFrame(render)
                oControl.update()
                rendererInstance.render(sceneInstance, cameraInstance)
              }

              render()
            }
          )

          return sceneInstance
        })

        document
          .getElementById('instance0')
          .appendChild(rendererInstance.domElement)

1 个答案:

答案 0 :(得分:0)

您需要为每个场景提供自己的相机和OrbitControls ...您可以在场景之间共享它们,但是它们都会从相同的角度进行渲染,我怀疑这是您想要的。

一个WebGLRenderer创建它自己的画布元素(称为domElement),因此您必须像div.appendChild(renderer.domElement)一样将每个元素附加到div。

如果有很多div,则为每个div创建渲染器可能会非常耗费资源。

在这种情况下,您可以为整个窗口(具有div大小的窗口)制作1个Renderer,并将其控制为仅在窗口的sub-div区域中进行渲染,但是它需要做的工作很少:

https://threejs.org/examples/webgl_multiple_elements.html

相关问题