How to integrate Pythreejs?

Does anyone familiar with pythreejs know how to integrate it into an anvil app? It basically uses ipython.display to render a scene, so I don’t know which component it corresponds to since it’s not exactly a photo or video.

Here’s a short sample of pythreejs

from pythreejs import *
import ipywidgets
from IPython.display import display

view_width = 600
view_height = 400

sphere = Mesh(
    SphereBufferGeometry(1, 32, 16),
    MeshBasicMaterial(color='red')
)

cube = Mesh(
    BoxBufferGeometry(1, 1, 1),
    MeshBasicMaterial(color='green'),
    position=[2, 0, 4]
)

camera = PerspectiveCamera( position=[10, 6, 10], aspect=view_width/view_height)


scene = Scene(children = [sphere,cube, camera,])

renderer = Renderer(camera=camera, scene=scene,controls=[OrbitControls(controlling=camera)],
                     width=view_width, height=view_height)

display(renderer)

Hi @atmalik1331 and welcome to the forum,

pythreejs module doesn’t make sense in Anvil.
You need to display components in the browser,
and the browser doesn’t know anything about the IPython display.
You’d end up writing that code in a server module/uplink with no way to send it to a client module.

Python in the browser isn’t the same as python on your local machine.


The good news… You can definitely achieve what you want in Anvil.

What you’ll want to do is look at a threejs, which is specifically written for the browser (and as you might have guessed from the name - pythonthreejs is based on this library).

Here is an example from our blog that uses threejs.

You can import threejs using

import anvil.js
THREE = anvil.js.import_from("https://cdn.skypack.dev/three@0.134.0")

# then probably
sphere = THREE.Mesh(...)
cube = THREE.Mesh(...)


But recommended to check out the blog post in combination with the threejs docs to work out how to implement your code with Anvil.
Then, if you get stuck, you can post a new question on the forum :grinning:, or the finished app as a show and tell :wink: .

1 Like

I had no idea there was an import_from option in anvil.js as well.

Never showed up in autocomplete.

One reason to explicitly mention it above :wink: - it’s very new - we added it around a month ago.
It should be in the autocomplete and here are some related docs on the subject.

1 Like