nannou-org / nannou

A Creative Coding Framework for Rust.
https://nannou.cc/
6.05k stars 306 forks source link

Choosing which canvas to use with the `wasm-experimental` feature #930

Open paolobettelini opened 1 year ago

paolobettelini commented 1 year ago

Hello,

I'm compiling nannou to wasm32 to draw onto a canvas. I noticed that the package always adds a new canvas at the end of the page (as far as I understand it), but I would like to draw wherever I want.

I did achieve this but I had to modify the nannou source, and I think it should be a feature.

window.rs

let canvas = window.canvas();

web_sys::window()
    .expect("window")
    .document()
    .expect("document")
    .get_element_by_id("container1")
    .expect("container1")
    //.body()
    //.expect("body")
    .append_child(&canvas)
    .expect("append_child");

Now the canvas will clearly be placed into a <div id="container1"></div>. Note that the program must be called after the document has fully loaded.

Thanks a lot

merlindru commented 1 year ago

Quick question, how did you get Nannou to add a canvas to the end of a page? Just by compiling it to WASM and then loading it from JS?

paolobettelini commented 1 year ago

Yes, I reckon I used this template template.

merlindru commented 1 year ago

@paolobettelini JulianCataldo/astro-nannou-starter solves this by embedding the nannou app in an iframe, like this:

<iframe src="./nannou-embed" />

nannou-embed:

<script>
    await import("../../crates/my-app/pkg/nannou_web_test.js").then(
        async ({ default: nannou }) => {
            await nannou().then((s: any) => {
                s.main_web();
            });
        }
    );
</script>
paolobettelini commented 1 year ago

Yes, for now I'm also embedding them in an iframe but it isn't really a clean solution and I would like to directly interact with multiple nannou objects on the same page (like: don't render if not visible, send a signal of some kind). Those are features I can''t quite get yet. Thank you that repository I will check it out