niivue / ipyniivue

A WebGL-powered Jupyter Widget for Niivue based on anywidget
BSD 2-Clause "Simplified" License
25 stars 8 forks source link

Exposing `nv.saveScene` on the python side #49

Open kolibril13 opened 6 months ago

kolibril13 commented 6 months ago

As @alexisthual suggested in today's meeting, it would be nice to expose nv.saveScene in order to generate static iamges. Here's an example on how nv.saveScene is used in niivue: https://github.com/niivue/ipyniivue-experimental/blob/main/original_gallery.md#color-maps-for-voxels

kolibril13 commented 5 months ago

Just investigated this issue a bit:

Python

class AnyNiivue(OptionsMixin, anywidget.AnyWidget):
    _save_scene = t.Bool(False).tag(sync=True)

    def save_scene(self):
        """Saves the current scene to a file"""
        self._save_scene = True

In widget.js

model.on("change:_save_scene", () => {
  nv.saveScene();
});

in notebook:

nv.save_scene()

This does work, but only once, as _save_scene is not being reset to False. After nv.saveScene(); is called, a pop-up window opens where one can define the filename.

Alternatively, there is also an option to directly pass a file name like this: nv1.saveScene("ScreenShot.png"); which could be also be implemented on the python side.

I guess the best approach here is to have a JSON traitlet like this _save_scene_as = t.Dict({"name": "screenshot.png", "counter": 1}).tag(sync=True)