JSFiddle - React, Tailwind, and code Playground

by kalmarsh80

HTML

<script src="http://deepliquid.com/projects/Jcrop/js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="http://jcrop-cdn.tapmodo.com/v0.9.12/css/jquery.Jcrop.min.css">
<img src="http://www.basekit.com/widget/image/placeholder.png" id="jcrop_target" style='max-width:300px;' />
<div id="userProfilePreviewDiv">
    <img src="http://www.basekit.com/widget/image/placeholder.png" id="userProfilePreview" />
</div>
<form action="#" method="post" onsubmit="return checkCoords();">
    <input type="file" name="userNewProfileImage" id="userNewProfileImage" />
    <input type="hidden" id="x" name="x" value="" />
    <input type="hidden" id="y" name="y" value="" />
    <input type="hidden" id="w" name="w" value="" />
    <input type="hidden" id="h" name="h" value="" />
    <input type="submit" value="Crop Image" style="float:left; width: 98px;" />
</form>

CSS

#userProfilePreviewDiv {
    width: 100px;
    height: 100px;
    overflow:hidden;
}

JavaScript

var jcrop_api;
setTimeout(function(){initJcrop();}, 3000);

function initJcrop() {
    jcrop_api = $.Jcrop('#jcrop_target', {
        onChange: showPreview,
        onSelect: showPreview,
        onRelease: hidePreview,
        aspectRatio: 1
    });
}

var $preview = $('#userProfilePreview');
// Our simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showPreview(coords) {
    if (parseInt(coords.w) > 0) {
        var rx = 100 / coords.w;
        var ry = 100 / coords.h;

        $preview.css({
            width: Math.round(rx * $("#jcrop_target").width()) + 'px',
            height: Math.round(ry * $("#jcrop_target").height()) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        }).show();
        updateCoords(coords);
    }
}

function updateCoords(c) {
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
}

function checkCoords() {
    if (parseInt(jQuery('#w').val()) > 0) return true;
    alert('Please select a crop region then press submit.');
    return false;
}

function hidePreview() {
    $preview.stop().fadeOut('fast');
}

$("#userNewProfileImage").live("change", function(){
    draw();
});

function draw() {
    var img = new Image(),
        f = document.getElementById("userNewProfileImage").files[0],
        url = window.URL || window.webkitURL,
        src = url.createObjectURL(f);

    img.src = src;
    img.onload = function () {
        $("#jcrop_target").attr('src', img.src);
        $("#userProfilePreview").attr('src', img.src);
        refreshJcrop(img.src);
    };
    return false;
}

function refreshJcrop(url) {
    jcrop_api.destroy();
    initJcrop();
}