Created
October 29, 2017 08:43
-
-
Save dusanmarsa/2ca9f1df36e14864328a2bb0b353332e to your computer and use it in GitHub Desktop.
JavaScript - Clipboard API - Paste image handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var IMAGE_MIME_REGEX = /^image\/(p?jpeg|gif|png)$/i; | |
var loadImage = function (file) { | |
var reader = new FileReader(); | |
reader.onload = function(e){ | |
var img = document.createElement('img'); | |
img.src = e.target.result; | |
var range = window.getSelection().getRangeAt(0); | |
range.deleteContents(); | |
range.insertNode(img); | |
}; | |
reader.readAsDataURL(file); | |
}; | |
document.onpaste = function(e){ | |
var items = e.clipboardData.items; | |
for (var i = 0; i < items.length; i++) { | |
if (IMAGE_MIME_REGEX.test(items[i].type)) { | |
loadImage(items[i].getAsFile()); | |
return; | |
} | |
} | |
e.PreventDefault() | |
} |
Great little gist. I turned this into a mini web-app to demonstrate pasting an image in a web page.
https://martindrapeau.github.io/image-clipboard/
Oh, Github didn't give me any notice about your comment but late answer better than no answer at all, right? 🙂 Glad to help. Nice app you got there.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great little gist. I turned this into a mini web-app to demonstrate pasting an image in a web page.
https://martindrapeau.github.io/image-clipboard/