user2228948
user2228948

Reputation: 33

drawImage with ImageElement

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 ?

Upvotes: 3

Views: 605

Answers (2)

Brandon
Brandon

Reputation: 2084

I thought I'd elaborate on the image onload syntax a little, in reference onError, onDone and cancelOnError...

readFile() {
    ImageElement image = new ImageElement(src: "plant.png");
    document.body.nodes.add(image);
    image.onLoad.listen(onData, onError: onError, onDone: onDone, cancelOnError: true);
  }

  onData(Event e) {
    print("success: ");
  }

  onError(Event e) {
    print("error: $e");
  }

  onDone() {
    print("done");
  }

Upvotes: 1

Pixel Elephant
Pixel Elephant

Reputation: 21383

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));

Upvotes: 6

Related Questions