Created
August 29, 2014 17:24
-
-
Save ragklaat/692653570e1eac4afed2 to your computer and use it in GitHub Desktop.
Drag & drop images to HTML5 canvas
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
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! :-)