However, I will not have a main loop in my Rust file. I call a Rust function (draw) from JS every user click. draw() will need to draw something from Rust (onto the canvas with context).
But if I set it up like I do, I will need to recreate the context each time the function is called:
#[wasm_bindgen] // called from JS on user click
pub fn draw(){
let context: Context = Context::new();
context.draw();
}
Is there a way to make it so context does not need to be initialized each time? I think the problem lies with wasm_bindgen.
You should add Context as argument to draw and export an extra function to js that creates the Context. I believe you have to annotate Context with #[bindgen] too for this to compile.
And just call draw from JS (on click) with the CanvasRenderingContext2d as argument. Although this doesn't give any explicit errors, it doesn't work. The console.log error shows:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'stroke')
Not sure how that can be fixed, or how you meant for it to be used?