Stdweb: extract Vec<u8> from a Value(Reference)

I have the following code:

        mlog!("good so far");
        let img_data = js! {
          let ctx = @{&canvas}.getContext("2d");
          let img_data = ctx.getImageData(0, 0, @{width}, @{height});

        mlog!("img_data: {:?}", img_data);

        let v: Vec<u8> = Vec::<u8>::try_from(img_data).ok()?;
        mlog!("typed array conversion worked");

In the Chrome console, I get the following:

good so far
Uint8ClampedArray(12920768) [ 0, 0, 0, ... ]
img_data: Reference(Reference(13071))
got none

What am I doing wrong here? From the js side, it is clear that the object is a Uint8ClampedArray. To rust, we are passing it a Value(Reference) -- yet why can't we get a Vec from this?

Looking at the source of the try_from impl you're using (link), it seems that it only works for something convertible to an stdweb::Array, and I'm guessing that this is not the case for Uint8ClampedArray.

As for how to solve it, I don't know.

I was under the (perhaps incorrect) impression that:


are the JS/Rust sides of the object.

A Uint8ClampedArray is definitely a TypedArray on the JS side, which is why I expected the above to work.

Okay, but is a TypedArray an Array? I may be wrong, but I'm guessing the answer is no.

Thus I recommend converting it to an stdweb::web::TypedArray and directly calling the provided to_vec method.

1 Like
  1. There is a confusion in the question. I had two versions of the code, one using TypedArray::<u8> (which I intended to paste), and one using Vec<u8> (which I actually pasted). This is my fault.

  2. Things appear to work now (crashing elsewhere).