2

I'm using Dart to develop a personal whiteboard Chrome app and it is sometimes useful to be able to quickly copy and paste an image (e.g. a slide from a presentation, a diagram or a handout) so that I can add notes over the image while teaching a class or giving a presentation.

How can I paste an image stored on the clipboard onto a canvas element in Dart?

Richard Ambler
  • 4,816
  • 2
  • 21
  • 38

1 Answers1

5

Actually, this answer to the same question for JS is almost directly applicable. A Dart translation might look something like:

import 'dart:html';

void main() {
  var can = new CanvasElement()
    ..width = 600
    ..height = 600
  ;

  var con = can.getContext('2d');

  document.onPaste.listen((e) {
    var blob = e.clipboardData.items[0].getAsFile();
    var reader = new FileReader();
    reader.onLoad.listen((e) {
      var img = new ImageElement()
        ..src = (e.target as FileReader).result;
      img.onLoad.listen((_) {
        con.drawImage(img, 0, 0);
      });
    });
    reader.readAsDataUrl(blob);
  });

  document.body.children.add(can);
}
Community
  • 1
  • 1
Richard Ambler
  • 4,816
  • 2
  • 21
  • 38
  • 1
    In the latest build of Dart (0.7.3_r27487), this code doesn't work... It seems that the item(_) method has been removed from the DataTransferItemList class... – Richard Ambler Oct 01 '13 at 01:28
  • I can't manage to generate the Paste event. I tried putting a breakpoint but it doesn't stop, so I suppose I'm missing something. – maugch Dec 03 '13 at 20:39
  • 1
    Update: as of Dart 1.1.1, the DataTransferItemList class is more analogous to other lists - instead of using e.clipboardData.items.item(index) we can simply use e.clipBoardData.items[index] (which makes more sense); the above code edited to reflect this change and currently working. – Richard Ambler Jan 26 '14 at 07:38
  • I had to get the item 1. With 0 I don't get any event (Load,LoadStart,etc..). I tried the paste event on the Document though. – maugch Jan 26 '14 at 13:21
  • 1
    Good point. Otherwise we have to make sure that the canvas has the focus; I've made the edit. Index zero is working for me... that's odd. – Richard Ambler Jan 27 '14 at 02:19
  • I tested it on Chrome (under Linux). That might be the reason? – maugch Jan 27 '14 at 08:18