image crop

image upload, crop

by Şuayip Ekmekci

HTML

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<input type="file" class="js-fileinput img-upload" accept="image/jpeg,image/png,image/gif">
<button class="js-export">Export</button>
<br>
<canvas class="js-editorcanvas hidden"></canvas>
<canvas class="js-previewcanvas"></canvas>

<div id="ex"></div>

JavaScript

function Uploader(options) {
  this.exceptionHandler = options.exceptions || console.log.bind(console);
  this.fileInput = document.querySelector(options.input);
  if (this.fileInput === null) {
    this.exceptionHandler("Could not find file input element: " + options.input);
    return null;
  }
  this.allowedTypes = options.types || ["gif", "jpg", "jpeg", "png"];
  this.reader = new FileReader();
}

Uploader.prototype.listen = function (callback) {
  if (!this.fileInput) {
    return;
  }
  this.fileInput.addEventListener("change", function(e) {
    // Do not submit the form
    e.preventDefault();
    // Make sure one file was selected
    if (!this.fileInput.files || this.fileInput.files.length !== 1) {
      this.exceptionHandler("Please select one file");
    } else {
      this.fileReaderSetup(this.fileInput.files[0], callback);
    }
  }.bind(this));
};

Uploader.prototype.fileReaderSetup = function(file, callback) {
  // Make sure the file is an image
  if (this.validFileType(file.type)) {
    // Read the image as base64 data
    this.reader.readAsDataURL(file);
    this.reader.addEventListener("load", function(e) {
      // Call the callback with the image's base64 data when it's available
      callback(e.target.result);
    });
  } else {
    this.exceptionHandler("Invalid file type, please use one of: " + this.allowedTypes);
  }
};

Uploader.prototype.validFileType = function(filename) {
  // Get the second part of the MIME type
  var extension = filename.split("/").pop().toLowerCase();
  // See if it is in the array of allowed types
  return this.allowedTypes.indexOf(extension) !== -1;
};

function Cropper(options) {
  this.exceptionHandler = options.exceptions || console.log.bind(console);
  if (!options.size) {
    this.exceptionHandler("Size field in options is required");
    return null;
  }
  this.imageCanvas = document.querySelector(options.canvas);
  if (this.imageCanvas === null) {
    this.exceptionHandler("Coud not find canvas element: "...