JSFiddle - React, Tailwind, and code Playground

by rangermeier

HTML

<script src="http://jcrop-cdn.tapmodo.com/v0.9.12/js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="http://jcrop-cdn.tapmodo.com/v0.9.12/css/jquery.Jcrop.min.css">
<input type="file" />
<img class="crop" style="display:none" />
<button type="submit" style="display:none">Upload</button>

JavaScript

var cropCoords,
    file,
    uploadSize = 360,
    previewSize = 500;

$("input[type=file]").on("change", function(){
    file = this.files[0];
    readFile(file, {
        width: previewSize,
        height: previewSize
    }).done(function(imgDataUrl, origImage) {
        $("input, img, button").toggle();
        initJCrop(imgDataUrl);
    }).fail(function(msg) {
        alert(msg);
    });
});

$("button[type=submit]").on("click", function(){
    $(this).text("Uploading...").prop("disabled", true);

    readFile(file, {
        width: uploadSize,
        height: uploadSize,
        crop: cropCoords
    }).done(function(imgDataURI) {
        var data = new FormData();
        var blobFile = dataURItoBlob(imgDataURI);
        data.append('file', blobFile);
        
        $.ajax({
            url: "/upload",
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function() {
                alert("Yay!");
            },
            error: function(xhr) {
                alert("Well, obviously we can't upload the file here."+
                      "This is what the data looks like: " +
                      imgDataURI.substr(0,128)+"...");
            }
        });
    });
});

/*****************************
show local image and init JCrop
*****************************/
var initJCrop = function(imgDataUrl){
    var img = $("img.crop").attr("src", imgDataUrl);
    
    var storeCoords = function(c) {
        cropCoords = c;
    };
    
    var w = img.width();
    var h = img.height();
    var s = uploadSize;
    img.Jcrop({
        onChange: storeCoords,
        onSelect: storeCoords,
        aspectRatio: 1,
        setSelect: [(w - s) / 2, (h - s) / 2, (w - s) / 2 + s, (h - s) / 2 + s]
    });
};

/*****************************
Read the File Object
*****************************/
var readFile = function(file, options) {
    var dfd = new $.Deferred();
   ...