wasm_bindgen::JsValue - constructing a map

From https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.HtmlCanvasElement.html

I need to use:

pub fn get_context_with_context_options(
    context_id: &str,
    context_options: &JsValue
) -> Result<Option<Object>, JsValue>

for the context_options argument, I want to pass it the Jsvalue of

{ premultipliedAlpha: false }

This involves constructing this value via:

The problem I run into is that I see constructing from f64 / bool / string -- but no way to construct a map.

How do I construct a wasm_bindgen::JsValue with a value of

{ premultipliedAlpha: False }


The easiest way is to use serde_json:

let options = JsValue::from_serde(&serde_json::json!({
    "premultipliedAlpha": false,

Note that you have to enable the feature serde-serialize in wasm-bindgen for this.

1 Like
  1. @anlumo 's solution definitely works for constructing the JsValue

  2. For anyone else running into this issue, for whatever JS/Browser reason, I had to end up constructing

{ "premultipliedAlpha": false, "alpha": false }

to make it work

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.