Browse Source

Add `get_camera` method to `ui.scene` (#3465)

* introduce `get_camera` method to get current camera parameters

* add a demo to the documentation

---------

Co-authored-by: Rodja Trappe <rodja@zauberzeug.com>
Falko Schindler 9 months ago
parent
commit
18a0d7ede2

+ 17 - 0
nicegui/elements/scene.js

@@ -424,6 +424,23 @@ export default {
         })
         .start();
     },
+    get_camera() {
+      return {
+        position: this.camera.position,
+        up: this.camera.up,
+        rotation: this.camera.rotation,
+        quaternion: this.camera.quaternion,
+        type: this.camera.type,
+        fov: this.camera.fov,
+        aspect: this.camera.aspect,
+        near: this.camera.near,
+        far: this.camera.far,
+        left: this.camera.left,
+        right: this.camera.right,
+        top: this.camera.top,
+        bottom: this.camera.bottom,
+      };
+    },
     resize() {
       const { clientWidth, clientHeight } = this.$el;
       this.renderer.setSize(clientWidth, clientHeight);

+ 8 - 0
nicegui/elements/scene.py

@@ -266,6 +266,14 @@ class Scene(Element,
                         self.camera.look_at_x, self.camera.look_at_y, self.camera.look_at_z,
                         self.camera.up_x, self.camera.up_y, self.camera.up_z, duration)
 
+    async def get_camera(self) -> Dict[str, Any]:
+        """Get the current camera parameters.
+
+        In contrast to the `camera` property,
+        the result of this method includes the current camera pose caused by the user navigating the scene in the browser.
+        """
+        return await self.run_method('get_camera')
+
     def _handle_delete(self) -> None:
         binding.remove(list(self.objects.values()))
         super()._handle_delete()

+ 18 - 0
website/documentation/content/scene_documentation.py

@@ -188,6 +188,24 @@ def orthographic_camera() -> None:
         scene.box()
 
 
+@doc.demo('Get current camera pose', '''
+    Using the `get_camera` method you can get a dictionary of current camera parameters like position, rotation, field of view and more.
+    This demo shows how to continuously move a sphere towards the camera.
+    Try moving the camera around to see the sphere following it.
+''')
+def camera_pose() -> None:
+    with ui.scene().classes('w-full h-64') as scene:
+        ball = scene.sphere()
+
+    async def move():
+        camera = await scene.get_camera()
+        if camera is not None:
+            ball.move(x=0.95 * ball.x + 0.05 * camera['position']['x'],
+                      y=0.95 * ball.y + 0.05 * camera['position']['y'],
+                      z=1.0)
+    ui.timer(0.1, move)
+
+
 @doc.demo('Custom Background', '''
     You can set a custom background color using the `background_color` parameter of `ui.scene`.
 ''')