Skip to content

Instantly share code, notes, and snippets.

@jahanson
Created March 3, 2014 17:42
Show Gist options
  • Save jahanson/9330339 to your computer and use it in GitHub Desktop.
Save jahanson/9330339 to your computer and use it in GitHub Desktop.
Paste image from clipboard to canvas. Convert to base64 image string.
<!DOCTYPE html>
<html>
<head>
<title>Paste Image</title>
<script type="text/javascript">
var imageObj = new Image();
window.onload = function() {
document.getElementById("pasteTarget").
addEventListener("paste", handlePaste);
var canvas = document.getElementById('canvasTarget');
var context = canvas.getContext('2d');
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
document.getElementById('base64image').value = canvas.toDataURL('image/png');
};
};
function handlePaste(e) {
for (var i = 0 ; i < e.clipboardData.items.length ; i++) {
var item = e.clipboardData.items[i];
console.log("Item type: " + item.type);
if (item.type.indexOf("image") != -1) {
//uploadFile(item.getAsFile());
imageObj.src = URL.createObjectURL(item.getAsFile());
} else {
console.log("Discarding non-image paste data");
}
}
}
function uploadFile(file) {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percentComplete = (e.loaded / e.total) * 100;
console.log("Uploaded: " + percentComplete + "%");
};
xhr.onload = function() {
if (xhr.status == 200) {
alert("Sucess! Upload completed");
} else {
alert("Error! Upload failed");
}
};
xhr.onerror = function() {
alert("Error! Upload failed. Can not connect to server.");
};
xhr.open("POST", "FileUploader", true);
xhr.setRequestHeader("Content-Type", file.type);
xhr.send(file);
}
</script>
</head>
<body>
<div style="width: 200px; height: 200px; background: grey" id="pasteTarget">
Click and paste here.
</div>
<div style="height:10px;"></div>
<canvas style="width: 200px; height: 200px; background: grey" id="canvasTarget"></canvas>
<h3>base64image</h3>
<textarea id="base64image" style="width:100%;height:300px;"></textarea>
</body>
</html>
@jahanson
Copy link
Author

jahanson commented Mar 3, 2014

Credit goes to http://mobiarch.wordpress.com/2013/09/25/upload-image-by-copy-and-paste/ for the original code. I just edited it for my uses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment