7

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.

Daniel Rodriguez
  • 1,443
  • 12
  • 19
narahd
  • 103
  • 2
  • 4

3 Answers3

10

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);
Adrian Ciura
  • 1,102
  • 1
  • 9
  • 14
Ali Akbar
  • 764
  • 1
  • 9
  • 13
  • Hi, I'm new to dart and when I try the image.on.load.add function I get an error stating that "load" is not a member of Events. Also the code hinting isn't very helpful with this. I'm using Dart Editor version 0.4.2_r20259 and Dart SDK version 0.4.2.8_r20259. – Hans Vn Mar 22 '13 at 15:24
  • 1
    Ok, I found out why: the dartlang core had an update... [Dart News & Updates](http://news.dartlang.org/2013/01/new-dom-event-streams-api.html). Now "image.on.load.add" should be written as "image.onLoad.listen". – Hans Vn Mar 22 '13 at 19:03
  • Since M1 of Dart was released the syntax has changed add "src:" before the filename ( new ImageElement(src:"my_image.png"); ) or this will cause a runtime error. – daftspaniel May 06 '13 at 18:31
9

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");
  }
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Brandon
  • 2,034
  • 20
  • 25
2

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");
}
Neeraj Kumar
  • 771
  • 2
  • 16
  • 37
Asdine
  • 2,856
  • 1
  • 16
  • 10