JSFiddle - React, Tailwind, and code Playground

by darkrose

HTML

<form id="form1" runat="server">
  <input type='file' id="imgInp" />

</form>
<div id="wrapper">
  <img id="blah" src="#" alt="your image" />
</div>

        
<textarea id="base64_output"></textarea>
<textarea id="data_output"></textarea>

CSS

#base64_output { width: 250px; height:100px}

#wrapper {width:320px;position:relative}
#blah {display:block;width:100%;height:100%}

JavaScript

///////// The rest logic
function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: (evt.clientX - rect.left),
    y: (evt.clientY - rect.top)
  };
}

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('#blah').attr('src', e.target.result);
      $('#base64_output').val(e.target.result);
			var $cc = $('<canvas style="cursor:crosshair;width:100%;height:100%;position:absolute;top:0;left:0">');
      var cc = $cc[0];
      cc.addEventListener('mousedown', function(e) {
        window.mousePos1 = getMousePos(cc, e);
        
      }, false);
      cc.addEventListener('mouseup', function(e){
      	window.mousePos2 = getMousePos(cc, e);
        var p1x = window.mousePos1.x;
        var p1y = window.mousePos1.y;
        var p2x = window.mousePos2.x;
        var p2y = window.mousePos2.y;
        if (p1x > p2x) {
          var tempx = p2x;
          p2x = p1x;
          p1x = tempx;
        }
        if (p1y > p2y) {
          var tempy = p2y;
          p2y = p1y;
          p1y = tempy;
        }
        var message = "area:" + p1x +',' + p1y + ',' + p2x + ',' + p2y;
        $('#data_output').val(message);
        
        // draw a preview rectangle:
        var w = p2x-p1x;var h = p2y-p1y;
        var ctx=cc.getContext("2d");
        ctx.rect(p1x,p1y,w,h);
        ctx.stroke();
        
      }, false);
      $('#wrapper').append($cc);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function(){
  readURL(this);
});