How to load an image in Dart

2020-02-12 06:03发布

问题:

I'm trying out the Dart Language and HTML5 Canvas element, but I'm stuck with one problem. I don't know how to load an image in Dart. I can get CanvasRenderingContext2D and with this I can call fillText() and fillRect() and everything works, but I am trying to figure out how to load an Image and draw with drawImage.

回答1:

Create and load the image

ImageElement image = new ImageElement(src: "my_image.png");
image.onLoad.listen((e) {
    // Draw once the image is loaded
});

Draw the above image on the canvas after it is loaded

context.drawImage(image, destX, destY);


回答2:

Newer image onload syntax:

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


回答3:

This is another way to do it :

void main() {
  ImageElement image = new ImageElement(src: "pic.png");
  img.onLoad.listen(onData);
  img.onError.listen(onError);
}

void onData(Event e) {
  print("Load success");
}

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


标签: dart