[英]Paste clipboard image to canvas
我有一個畫布,我需要用戶能夠將圖像粘貼到它上面。 我希望這是跨瀏覽器。 我只想使用 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 畫布,這變得容易多了。 您應該能夠使用畫布的“放置”事件或窗口的“粘貼”事件來完成此操作。 以下代碼片段改編自我用來完成此操作的打字稿類。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.