I’d like to create some 2D UI for my Babylon.JS Editor project. I’m hoping to meet the following requirements:
- UI should be visible in the BJS Editor viewport even when not in “play” mode.
- Use HTML/CSS to define and style the UI.
I’m having trouble figuring out how to accomplish this. Below are approaches I’ve tried. If anyone has other recommendations, I’d love to hear them.
Approach A:
Add the UI HTML and CSS to the workspace’s “index.html” file.
This works great when the project is run using the “Run” button (which previews the scene in a popup window) or when the project is loaded in an external browser. However, it does not display any UI when running the scene directly in the viewport.
Approach B:
Use a script to dynamically create the HTML elements at runtime.
Like the above approach, this one works fine when using the “Run” button (popup preview) or an external browser. It does have an effect when pressing “Play” to preview in the viewport. However, the behavior is not what I would expect and not very helpful. It seems that when a scene script accesses “document.body”, it resolves to the body element of the whole editor and not the body element of the sandboxed document displayed in the viewport iframe. This prevents the UI from being positioned relative to the viewport and instead is muddled in with other editor elements.
For example, when I use the script below to add a div with a red border (as a stand-in for my UI), I get the wacky result you see in the subsequent image…
public onInitialize(): void {
// Curiously, the "document.body" below resolves to the body of the
// whole BJS Editor, not the body element of the viewport sandbox
// document!
console.log(document.body);
const gui = document.createElement('div');
gui.style.position = 'absolute';
gui.style.top = '0';
gui.style.left = '0';
gui.style.width = '300px';
gui.style.height = '200px';
gui.style.border = '3px solid red';
document.body.append(gui);
}