JSFiddle - React, Tailwind, and code Playground

by neonDog

HTML

<input type="file" accept=".jpg,.jpeg.,.gif,.png,.mov,.mp4" />

<p><strong>Select a video or image file</strong><br /><br />Supported browsers (tested): Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+)</p>

<div></div>

CSS

div {
  line-height: 200px;
}

img {
  max-width: 200px;
  max-height: 200px;
  padding: 5px;
  vertical-align: middle;
  text-align: center;
}

@supports (object-fit: cover) {
  img {
    width: 200px;
    height: 200px;
    object-fit: cover;
  }
}

JavaScript

const cropImage = function(image, size) {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    
    let width = image.width;
    let height = image.height;

    if (image instanceof HTMLVideoElement) {
        width = image.videoWidth;
        height = image.videoHeight;
    }

    canvas.width = width * size;
    canvas.height = height * size;
    
    context.drawImage(image,
        0,
        0,
        width,
        height,
        0,
        0,
        canvas.width,
        canvas.height
    );
    
    return canvas;
}


const getFileThumbnail = async function (file, returnImg = true, size=0.3, fileReader=null) {

    fileReader = fileReader || new FileReader();

    return new Promise(function (resolve, reject) {

        if (file.type.match('image')) {

            fileReader.onload = function () {

                let image = new Image();
                
                image.onload = function () {
                    const result = cropImage(image, size);
                    image.remove();
                    image = null;
                    resolve(result);
                }

                image.src = fileReader.result;

            };
            fileReader.readAsDataURL(file);

        } else {
    
            fileReader.onload = function () {
                const blob = new Blob([fileReader.result], { type: file.type });
                const url = URL.createObjectURL(blob);
                let video = document.createElement('video');

                const timeupdate = function () {

                    const result = returnImg ? snapImage() : document.body.append(video);

                    if (result) {

                        video.removeEventListener('loadeddata', timeupdate);
                        video.removeEventListener('timeupdate', timeupdate);

                        if (returnImg) {
                            video.remove();
                            video = null;
       ...