drawImage with ImageElement

Issue

Working: (document has a img tag with id=”img” src=”img.png”, and it works)

  void test() {
    ImageElement img = query('#img');
    context.drawImage(img, 0, 0);
  }

Not Working:

  void test() {
    ImageElement img = new ImageElement(src: 'img.png');
    context.drawImage(img, 0, 0);
  }

so, why can’t I use ‘new ImageElement’ instead of ‘query’ from the document ?

Solution

The problem is that the image hasn’t loaded by the time you call drawImage (as opposed to when it is embedded in the page and loads before the dart code runs). You should listen for the onLoad stream and only draw the image once it is loaded:

  ImageElement img = new ImageElement(src: "img.png");
  img.onLoad.listen((value) => context.drawImage(img, 0, 0));

Answered By – Pixel Elephant

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *