Pregunta

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 ?

¿Fue útil?

Solución

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

Otros consejos

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");
  }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top