Created
December 22, 2015 14:30
-
-
Save avivbeeri/df171df041029e59d6d9 to your computer and use it in GitHub Desktop.
Paste to canvas demo
This file contains 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
<body> | |
<canvas id="canvas"></canvas> | |
<div style="width: 200px; height: 200px; background: grey" id="pasteTarget"> | |
Click and paste here. | |
</div> | |
</body> |
This file contains 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
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