Paste clipboard image to canvas

泄露秘密 提交于 2019-12-03 03:59:29

This works fine in Chrome, though as of yet I haven't been able to figure out how to get it to work in Firefox. You can use this jQuery plugin to detect clipboard pastes. I'll assume you know how to draw the image once you have the data from the clipboard.

# 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)

To use:

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

As far as I know, there is no way to do this just with JavaScript and HTML. However, this blog post describes achieving this using a Java applet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!