Skip to content

Commit

Permalink
Add get_camera method to ui.scene (#3465)
Browse files Browse the repository at this point in the history
* introduce `get_camera` method to get current camera parameters

* add a demo to the documentation

---------

Co-authored-by: Rodja Trappe <rodja@zauberzeug.com>
  • Loading branch information
falkoschindler and rodja authored Aug 10, 2024
1 parent 5f52a8a commit 18a0d7e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
17 changes: 17 additions & 0 deletions nicegui/elements/scene.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 8 additions & 0 deletions nicegui/elements/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,14 @@ def move_camera(self,
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()
Expand Down
18 changes: 18 additions & 0 deletions website/documentation/content/scene_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
''')
Expand Down

0 comments on commit 18a0d7e

Please sign in to comment.