How do I initialize CanvasRenderingContext2d only once, globally?

Currently I create a CanvasRenderingContext2d as follows:

impl Context{
    fn new() -> Context{
        let context ..
        Context{ context }
    }
}

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.

I dont really follow sorry.

What I made now is:

#[wasm_bindgen]
pub fn draw(context: CanvasRenderingContext2d) {
    context.stroke();
}

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?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.