JSFiddle - React, Tailwind, and code Playground

by Lazaro Contreras

HTML

<input type="file" class="form-control" id="imagen" name="imagen[]" onchange="preview_images();" multiple />

CSS

.imgUp {
  font-family: Arial;
  position: relative;
  display: inline-flex;
  overflow: hidden;
  border-radius: 5px;
  user-select: none;
}

.imgUp a {
  opacity: 0;
  position: absolute;
  top: 0;
  right: 0;
  background: #333;
  padding: 5px;
  color: white;
  cursor: pointer;
  height: 20px;
  width: 20px;
  text-align: center;
  z-index: 10;
  border-radius: 0 0 0 5px;
  transition: 0.2s all ease-out;
}

.imgUp:hover a {
  opacity: 1;
}

JavaScript

//var ad = document.querySelector('a');
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');

function preview_images() {
  var imgFiles = document.getElementById("imagen").files;

  [...imgFiles].forEach(function(imgFile) {
    var div = document.createElement('div');
    var img = document.createElement("img");
    img.setAttribute('src', URL.createObjectURL(imgFile));
    add(img, div);
    img.onload = function() {
      canvas.width = 500;
      canvas.height = 200;

      //ctx.drawImage(img, canvas.width / 2 - ((canvas.height * img.width)/img.height) / 2, 0, (canvas.height * img.width)/img.height, canvas.height);
      
      ctx.drawImage(img, 0, canvas.height / 2 - ((canvas.width * img.height)/img.width) / 2, canvas.width, (canvas.width * img.height)/img.width);

      var base64 = canvas.toDataURL('image/jpeg', 0.85).replace("data:image/png;base64,", "").replace("data:image/jpeg;base64,", "");
      var blob = b64toBlob(base64, 'image/jpeg');
      var url = URL.createObjectURL(blob);
      var img2 = document.createElement("img");
      img2.setAttribute('src', url);

      div.replaceChild(img2, img);
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  });
}

function add(img, div) {
  var a = document.createElement('a');
  div.className = 'imgUp';
  a.innerHTML = 'x';
  a.onclick = function() {
    var div = document.querySelectorAll('.imgUp');
    remove(div[index(this, 'a')]);
  }
  div.appendChild(img);
  div.appendChild(a);
  document.body.appendChild(div);
}

function remove(e) {
  e.remove();
}

function index(obj, type) {
  var items = document.getElementsByTagName(type);
  for (var i = 0; i < items.length; i++) {
    if (items[i] == obj) {
      return i;
    }
  }
}




const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice =...