Skip to content

Instantly share code, notes, and snippets.

@lyo
Forked from ragklaat/drag_n_drop.html
Last active June 21, 2020 04:08
Show Gist options
  • Save lyo/26109c15ebcdb331d0b132ef39eb9a66 to your computer and use it in GitHub Desktop.
Save lyo/26109c15ebcdb331d0b132ef39eb9a66 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();
img.src = 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment