Paste clipboard image to canvas

2019-03-16 20:47发布

问题:

I have a canvas that i need the users to be able to paste an image onto. I would like this to be cross browser. I would like only to use html/javascript. I would also be willing to use a flash object.

回答1:

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


回答2:

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