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 w开发者_运维百科illing to use a flash object.
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
This got a lot easier with HTML5 canvases. You should be able to use the canvas's "drop" event or the window's "paste" event to accomplish this. The below code snippets are adapted from a typescript class that I use to accomplish this.
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);
}
}
精彩评论