Search code examples
three.jsaframe

Aframe update camera fov at runtime


I've been trying to update properties of the camera on the fly to no avail - really don't want to setup multiple cameras and switch between them.

    AFRAME.registerComponent("camera-controller", {

        init: function() {
            this.el.addEventListener('model-loaded', this.update.bind(this));
        },
    update: function() {
        var data = this.data;
        var el = this.el;

        // el.fov = 75;
        el.object3D.el.components.camera.data.fov = 20;
        el.updateProjectionMatrix();
        console.log(el.object3D.el.components.camera.data.fov);

    }
});

camera.fov just returns undefined and updateProjectionMatrix() is not a function.


Solution

  • You can simply update the [camera]s FOV property via setAttribute("camera", "fov", newFOV). Something like this:

    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
    <script>
      AFRAME.registerComponent("foo", {
        init: function() {
          // grab the camera
          const cam = document.querySelector("[camera]")
          // on click
          document.body.addEventListener("click", e => {
            // grab the current FOV
            const fov = cam.getAttribute("camera").fov
            // update the camera with the new FOV
            cam.setAttribute("camera", "fov", fov == 80 ? 120 : 80)
          })
        }
      })
    </script>
    <a-scene foo>
      <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
      <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder>
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
      <a-sky color="#ECECEC"></a-sky>
    </a-scene>


    You can make the transition animated with the standard animation component (animating camera.fov) - here's an example with one animation (to utilize the above js logic, you could make two animations if you prefer a more 'declarative' style).