Using @:bitmap on html5 target

Hey folks, been a while. I know this issue has been discussed a lot but all the answers I can find are years old.

When I do something like this:

@:bitmap("image.png") class MyImage extends BitmapData {}
// later
new MyImage(0, 0);

The resulting bitmapdata is always 0x0 and doesn’t render. I understand this has something to do with images being loaded async in the browser (the image does come through if I look in the chrome network pane).

I know the OpenFL Assets class is the simple way to get around this – it’s what I’m using right now. However, what I would like to do is embed a few select images inside a library so I don’t have to mess around with adding asset paths in my project that will use that library. Ideally, I would create a new AssetLibrary class that provides these embedded images.

Is there any way to make @:bitmap embeds work in the HTML5 target?

Hi Jacob!

Unfortunately it is not possible to synchronously load an image on HTML5… even if we embed the bytes or write it as Base64!

It works like this:

  1. Creating new MyImage() will quietly load in the background. If you use this BitmapData with a Bitmap I believe it will show once the data has loaded.
  2. After loading the first time, it will keep a copy saved in memory so requesting a new MyImage() a second time will be available right away
  3. Loading bitmap data this way does not provide a callback for when it is loaded (unlike Loader, BitmapData.loadFromFile or using openfl.utils.Assets), though as a workaround you can create a timer to poll for when the width and height is greater than zero

Thanks Joshua, that helps a lot. I assume the same is true for font embeds? I was having similar trouble with those.

With this knowledge, it seems like I should be able to be able to make an AssetLibrary that polls until the bitmaps are finished loading, and then makes them available through the standard Assets.loadBitmapData method – the one thing is that I wouldn’t want them to be accessed before they were fully processed; ideally hooking into the preloader in some way. Is it possible to register a custom AssetLibrary that also informs the preloader progress?