MvG MvG - 25 days ago 17
Javascript Question

createImageBitmap alternative on Safari

I'd like to generate images in a bit of asm.js code running on a web worker. And I'd like to regularly composite the latest state of that computation onto a user-visible 2d canvas, together with some other content. Currently I have code which


  1. constructs an
    ImageData
    object using its constructor, based on a portion of the array buffer used by the asm.js code,

  2. calls
    createImageBitmap
    to turn the
    ImageData
    into an
    ImageBitmap
    ,

  3. transfers that image bitmap from the worker to the GUI thread and

  4. uses that
    ImageBitmap
    as an argument to
    CanvasRenderingContext2D.drawImage
    .



Things work nicely in recent Chrome and Firefox, but Safari 9.1.3 apparently has no
createImageBitmap
function. How would I do something like the above in a way that works on Safari?

Is there some low-cost encoding of images, short of creating a
data:image/png…
for it? Is there some other way to turn a byte array into something you can feed to
drawImage
?

By the way: http://caniuse.com/ currently doesn't list this feature. There is a feature request which you can

Answer

Is there some other way to turn a byte array into something you can feed to drawImage?

You can post the ArrayBuffer of Uint8ClampedArray object to main thread; at main thread substitute using .putImageData() for .drawImage(). As indicated by @Kaiido, it is not necessary to create an ImageData object at Worker

var imgBytes = new Uint8ClampedArray(buffer, offset);
postMessage(imgBytes.buffer, [imgBytes.buffer]);

at main thread

worker.onmessage = function(e) {
  console.log(e.data); // `ArrayBuffer`
  ctx.putImageData(new ImageData(new Uint8ClampedArray(e.data), width, height), 0, 0);
}

http://plnkr.co/edit/N0v1YQHQX2rdFfHcOKeR?p=preview

Comments