imagecachingcanvasdart2d-context-api

How do you cache images to be drawn later in canvas2d in dart?


So, I got how to draw images in canvas using dart, which goes something like this:

    ///create the image element with given source
    ImageElement myImage = new ImageElement(src:"myImage.png");

    ///load the image
    myImage.onLoad.listen((event){
         ///when the image is loaded, draw it
         myContext.drawImage(myImage, 0, 0);
    });

But, how do you draw an image at a later date?

As in, say I have a list of images:

    List<ImageElement> myImageList;

I want to then load all my image elements one by one given their source. Then when that's done, whenever I feel like it, I can just go:

    myContext.drawImage(myImageList[i], x, y);

without this code being inside the onLoad.listen method.


Solution

  • You can use Future.wait to wait onLoad on every images :

    Future.wait(myImageList.map((e) => e.onLoad.single)).then((_){
      myContext.drawImage(myImageList[i], x, y);
      // or call function that assumes that images are loaded
    });