JSFiddle - React, Tailwind, and code Playground
by SupunKavinda
HTML
<html>
<body style="padding:100px;background-color:#fafafa;font-family: 'Segoe UI', sans-serif;">
<div id="drop-region">
<div class="drop-message">
Drag & Drop images or click to upload
</div>
<div id="image-preview"></div>
</div>
</body>
</html>
CSS
#drop-region {
background-color: #fff;
border-radius:20px;
box-shadow:0 0 35px rgba(0,0,0,0.05);
width:400px;
padding:60px 40px;
text-align: center;
cursor:pointer;
transition:.3s;
}
#drop-region:hover {
box-shadow:0 0 45px rgba(0,0,0,0.1);
}
#image-preview {
margin-top:20px;
}
#image-preview .image-view {
display: inline-block;
position:relative;
margin-right: 13px;
margin-bottom: 13px;
}
#image-preview .image-view img {
max-width: 100px;
max-height: 100px;
}
#image-preview .overlay {
position: absolute;
width: 100%;
height: 100%;
top: 0;
right: 0;
z-index: 2;
background: rgba(255,255,255,0.5);
}
JavaScript
var // where files are dropped + file selector is opened
dropRegion = document.getElementById("drop-region"),
// where images are previewed
imagePreviewRegion = document.getElementById("image-preview");
// open file selector when clicked on the drop region
var fakeInput = document.createElement("input");
fakeInput.type = "file";
fakeInput.accept = "image/*";
fakeInput.multiple = true;
dropRegion.addEventListener('click', function() {
fakeInput.click();
});
fakeInput.addEventListener("change", function() {
var files = fakeInput.files;
handleFiles(files);
});
function preventDefault(e) {
e.preventDefault();
e.stopPropagation();
}
dropRegion.addEventListener('dragenter', preventDefault, false)
dropRegion.addEventListener('dragleave', preventDefault, false)
dropRegion.addEventListener('dragover', preventDefault, false)
dropRegion.addEventListener('drop', preventDefault, false)
function handleDrop(e) {
var dt = e.dataTransfer,
files = dt.files;
if (files.length) {
handleFiles(files);
} else {
// check for img
var html = dt.getData('text/html'),
match = html && /\bsrc="?([^"\s]+)"?\s*/.exec(html),
url = match && match[1];
if (url) {
uploadImageFromURL(url);
return;
}
}
function uploadImageFromURL(url) {
var img = new Image;
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
img.onload = function() {
c.width = this.naturalWidth; // update canvas size to match image
c.height = this.naturalHeight;
ctx.drawImage(this, 0, 0); // draw in image
c.toBlob(function(blob) { // get content as PNG blob
// call our main function
handleFiles( [blob] );
}, "image/png");
};
img.onerror = function() {
alert("Error in uploading");
}
img.crossOrigin = ""; // if from different origin
...