Skip to content

Instantly share code, notes, and snippets.

@ragklaat
Created August 29, 2014 17:24
Show Gist options
  • Save ragklaat/692653570e1eac4afed2 to your computer and use it in GitHub Desktop.
Save ragklaat/692653570e1eac4afed2 to your computer and use it in GitHub Desktop.
Drag & drop images to HTML5 canvas
<!doctype html>
<html>
<head>
<title>Drag n drop test</title>
<style type="text/css">
body {text-align: center; padding-top: 100px;}
em {position: absolute; bottom: 0; right: 0}
canvas { border: 1px solid black; }
</style>
<script type="text/javascript">
window.ondragover = function(e) {e.preventDefault()}
window.ondrop = function(e) {e.preventDefault(); draw(e.dataTransfer.files[0]); }
function draw(file){
var img =new Image();
// URL @ Mozilla, webkitURL @ Chrome
img.src = (window.webkitURL ? webkitURL : URL).createObjectURL(file);
var canvas=document.getElementById("image_canvas");
var ctx = canvas.getContext("2d");
// call ctx.drawImage when the image got loaded
img.onload = function() {
// ctx.drawImage(img, 0, 0);
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height); // stretch img to canvas size
}
}
</script>
</head>
<body>
<div>DROP!</div>
<canvas id="image_canvas" width="200" height="200"></canvas>
</body>
</html>
@lyo
Copy link

lyo commented Jun 21, 2020

good code snippet. I'll use this. 😺
'webkitURL' is deprecated in modern chrome. i fix it.
https://gist.github.com/lyo/26109c15ebcdb331d0b132ef39eb9a66/revisions#diff-46cca76c5248b046fecc71fc97bd6855

@ragklaat
Copy link
Author

ragklaat commented Jun 22, 2020

'webkitURL' is deprecated in modern chrome. i fix it.

Thanks! :-)

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