将剪贴板图像粘贴到画布上

Paste clipboard image to canvas

本文关键字:剪贴板 图像      更新时间:2023-09-26

我有一个画布,我需要用户能够粘贴图像到。我想这是跨浏览器。我想只使用html/javascript。我也愿意使用flash对象

这在Chrome中工作得很好,尽管到目前为止我还没能弄清楚如何让它在Firefox中工作。你可以使用这个jQuery插件来检测剪贴板的粘贴。我将假设您知道如何从剪贴板获取数据后绘制图像。

# jquery.paste_image_reader.coffee
(($) ->
  $.event.fix = ((originalFix) ->
    (event) ->
      event = originalFix.apply(this, arguments)
      if event.type.indexOf('copy') == 0 || event.type.indexOf('paste') == 0
        event.clipboardData = event.originalEvent.clipboardData
      return event
  )($.event.fix)
  defaults =
    callback: $.noop
    matchType: /image.*/
  $.fn.pasteImageReader = (options) ->
    if typeof options == "function"
      options =
        callback: options
    options = $.extend({}, defaults, options)
    this.each () ->
      element = this
      $this = $(this)
      $this.bind 'paste', (event) ->
        found = false
        clipboardData = event.clipboardData
        Array::forEach.call clipboardData.types, (type, i) ->
          return if found
          return unless type.match(options.matchType)
          file = clipboardData.items[i].getAsFile()
          reader = new FileReader()
          reader.onload = (evt) ->
            options.callback.call(element, file, evt)
          reader.readAsDataURL(file)
          found = true
)(jQuery)
使用:

$("html").pasteImageReader
  callback: (file, event) ->
    # Draw the image with the data from
    # event.target.result

据我所知,仅使用JavaScript和HTML是无法做到这一点的。然而,这篇博文描述了使用Java applet

实现这一点。

使用HTML5画布,这变得容易得多。你应该能够使用画布的"drop"事件或窗口的"粘贴";事件来完成此操作。下面的代码片段改编自我用来完成此任务的typescript类。

this.canvas.addEventListener("drop", onDrop);
window.addEventListener("paste", onPaste);
function onDrop(event: DragEvent): void {
  event.preventDefault();
  const file = event.dataTransfer.files[0];
  this.createRasterFromFile(file);
}
function onPaste(event: ClipboardEvent): void {
  event.preventDefault();
  event.stopPropagation();
  const file = event.clipboardData.items[0].getAsFile();
  this.createRasterFromFile(file);
}
function createRasterFromFile(file: File): void {
  if (file && (file.type == 'image/png' || file.type == 'image/jpeg')) {
    const reader = new FileReader();
    reader.onload = function () {
      // Image data stored in reader.result
    }.bind(this);
    reader.readAsDataURL(file);
  }
}