How can I paste an image from the clipboard onto a

2019-05-10 22:54发布

问题:

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?

回答1:

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