Skip to content

Commit

Permalink
Merge pull request #6 from Hepheir/feature-2
Browse files Browse the repository at this point in the history
Implement of image paste-able direct from clipboard #2
  • Loading branch information
hepheir authored Nov 17, 2020
2 parents bf88186 + eacce50 commit b0edad8
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions js/script.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
function arrayBuffer2Base64(arraybuffer) {
return 'data:image/png;base64,' + base64ArrayBuffer(arraybuffer);
}

function openFile() {
var input = document.createElement("input");
input.type = "file";
Expand All @@ -7,9 +11,34 @@ function openFile() {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => {
var bufferArray = reader.result;
output.innerText = 'data:image/png;base64,' + base64ArrayBuffer(bufferArray);
output.innerText = arrayBuffer2Base64(reader.result);
};
};
input.click();
}

window.addEventListener('paste', evt => {
// works on Chrome
navigator.clipboard.read().then(data => {
/* data:
* - Array of items,
* each of the items are
* `{types: ["image/png", ...], ...}`
* with prototype methods such as `getType()`
*
* Document for Clipboard API:
* - https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
*/
for (let i=0; i<data.length; i++) {
if (data[i].types[0] == "image/png") {
data[i].getType("image/png")
.then(blob => blob.arrayBuffer())
.then(arraybuffer => {
output.innerText = arrayBuffer2Base64(arraybuffer);
});
}
}
});

// TODO: test on other browsers
})

0 comments on commit b0edad8

Please sign in to comment.