Saving and Loading Camera's Position and Rotation - not working

Ok so I have a threeJS app setup and working, some of the code of myinit() function is below. I setup my scene in a standard way I just use OrbitControls.

controls = new THREE.OrbitControls( camera );
controls.update();

Now what I am trying to do is to save the cameras location in HTML5 storage and then load then up again as I need the same exact viewpoint.

function saveCameraLocation(){

  localStorage.setItem("camera.position.x", camera.position.x);
  localStorage.setItem("camera.position.y", camera.position.y);
  localStorage.setItem("camera.position.z", camera.position.z);

  localStorage.setItem("camera.rotation.x", camera.rotation.x);
  localStorage.setItem("camera.rotation.y", camera.rotation.y);
  localStorage.setItem("camera.rotation.z", camera.rotation.z);
}

The load function is:

function loadCameraLocation(){

  camera.setRotationFromEuler(new THREE.Euler(
    parseFloat(localStorage.getItem("camera.rotation.x")),
    parseFloat(localStorage.getItem("camera.rotation.y")),
    parseFloat(localStorage.getItem("camera.rotation.z")), 'XYZ' ));

  camera.position.x = parseFloat(localStorage.getItem("camera.position.x"));
  camera.position.y = parseFloat(localStorage.getItem("camera.position.y"));
  camera.position.z = parseFloat(localStorage.getItem("camera.position.z"));
  camera.updateProjectionMatrix();
}

This is not working. The position updates but the rotation does nothing.

Why is that ?

I should be sufficient if you just do:

camera.rotation.x = parseFloat(localStorage.getItem("camera.rotation.x"));
camera.rotation.y = parseFloat(localStorage.getItem("camera.rotation.y"));
camera.rotation.z = parseFloat(localStorage.getItem("camera.rotation.z"));

instead of using Object3D.setRotationFromEuler().

1 Like