Skip to content

Instantly share code, notes, and snippets.

@avivbeeri
Created December 22, 2015 14:30
Show Gist options
  • Save avivbeeri/df171df041029e59d6d9 to your computer and use it in GitHub Desktop.
Save avivbeeri/df171df041029e59d6d9 to your computer and use it in GitHub Desktop.
Paste to canvas demo
<body>
<canvas id="canvas"></canvas>
<div style="width: 200px; height: 200px; background: grey" id="pasteTarget">
Click and paste here.
</div>
</body>
function handlePaste(e) {
for (var i = 0 ; i < e.clipboardData.items.length ; i++) {
var item = e.clipboardData.items[i];
console.log("Item: " + item.type);
if (item.type.indexOf("image -1")) {
console.log(blobToDataURL(item.getAsFile()));
blobToDataURL(item.getAsFile(), function (result) {
loadCanvas(result);
});
} else {
console.log("Discardingimage paste data");
}
}
}
//**blob to dataURL**
function blobToDataURL(blob, callback) {
var a = new FileReader();
a.onload = function(e) {if (callback) callback(e.target.result);}
a.readAsDataURL(blob);
}
function loadCanvas(dataURL) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// load image from data url
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 0, 0);
};
imageObj.src = dataURL;
}
document.getElementById("pasteTarget").addEventListener("paste", handlePaste);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment