drawImage with ImageElement

夙愿已清 提交于 2019-12-10 19:16:09

问题


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 ?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/16739624/drawimage-with-imageelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!