Handle image file drop on canvas
<!DOCTYPE html> <html> <head> <title>Testing Drag and Drop</title> </head>/*from w ww. ja v a 2s.co m*/ <body> <canvas id="drop"></canvas> <script> let drop = document.getElementById('drop'); let ctx = drop.getContext('2d'); // Tells the browser that we *can* drop on this target drop.addEventListener('dragover', preventDefault, false); drop.addEventListener('dragenter', preventDefault, false); drop.addEventListener('drop', handleDrop, false); function preventDefault(e) { if (e.preventDefault) { e.preventDefault(); } return false; } function handleDrop(e) { e.stopPropagation(); // Stops some browsers from redirecting. e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. let file = e.dataTransfer.files[0]; let image = new Image(); reader = new FileReader(); reader.readAsDataURL(file); reader.onload = (function(theFile) { return function(e) { image.src = e.target.result; }; })(file); image.onload = function() { ctx.drawImage(image, 0, 0); }; } </script> </body> </html>