polotno-project / polotno-board

Roadmap and bug-tracker for the Polotno project.
https://polotno.dev/
9 stars 1 forks source link

on('change') event fires before image is loaded #22

Closed iamsterdam800 closed 3 years ago

iamsterdam800 commented 3 years ago

When I use on('change') event to update the preview on e.g. changing the background or adding an image, the image rendered with store.toDataURL() often does not contain the image being loaded. I even added a delay of 500 ms between on('change') and rendering the store. But that didn't help much.

https://youtu.be/OpqPJyvBPwM

Is it possible to fire the 'change' event when the image loading is completed? or can I use some other means to detect that all images were loaded?

lavrton commented 3 years ago

change is designed to be triggered on any data changes. If you want to wait for resource loading, you can use await store.waitLoading(). https://polotno.dev/docs/store-overview/#storewaitloading

iamsterdam800 commented 3 years ago

Thanks Anton! Using await store.waitLoading() indeed helped to render the preview properly.

I added some code to handle the "concurrent" changes (those that happen while the store is still loading). With this code it skips all the in-between changes, that don't need to be rendered. Not sure if there's a better way of doing it. But with this the rendering is flawless :) although a bit "delayed"..

    // update on change
    let busy = false;
    let concurrentChange = false;
    store.on("change", async () => {
      concurrentChange = true;
      if (busy) return;
      busy = true;
      while (concurrentChange) {
        concurrentChange = false;
        await store.waitLoading();
      }
      setContent(store.toDataURL());
      busy = false;
    });