Skip to content

Instantly share code, notes, and snippets.

@DaxChen
Created March 28, 2016 03:59
Show Gist options
  • Select an option

  • Save DaxChen/f7d9fc5684ad75505c25 to your computer and use it in GitHub Desktop.

Select an option

Save DaxChen/f7d9fc5684ad75505c25 to your computer and use it in GitHub Desktop.

Revisions

  1. @dominictobias dominictobias revised this gist Oct 10, 2015. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    // From README of: https://github.com/DominicTobias/react-image-crop

    loadImage: function(src, callback) {
    var image = new Image();
    image.onload = function(e) {
  2. @dominictobias dominictobias renamed this gist Oct 10, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. @dominictobias dominictobias created this gist Oct 10, 2015.
    50 changes: 50 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    loadImage: function(src, callback) {
    var image = new Image();
    image.onload = function(e) {
    callback(image);
    image = null;
    };

    image.src = src;
    },

    cropImage: function(imgDest, imgSrc, crop) {
    this.loadImage(imgSrc, cropAfterLoad.bind(this));

    function cropAfterLoad (loadedImg) {
    var imageWidth = loadedImg.naturalWidth;
    var imageHeight = loadedImg.naturalHeight;

    var cropX = (crop.x / 100) / 100 * imageWidth;
    var cropY = (crop.y / 100) / 100 * imageHeight;

    var cropWidth = (crop.width / 100) / 100 * imageWidth;
    var cropHeight = (crop.height / 100) / 100 * imageHeight;

    var canvas = document.createElement('canvas');
    canvas.width = cropWidth;
    canvas.height = cropHeight;
    var ctx = canvas.getContext('2d');

    ctx.drawImage(loadedImg, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);

    if (HTMLCanvasElement.prototype.toBlob) {
    console.info('It looks like Chrome now supports HTMLCanvasElement.toBlob.. time to uncomment some code!');
    }

    // canvas.toBlob will be faster and non-blocking but is currently only supported in FF.
    // canvas.toBlob(function(blob) {
    // var url = URL.createObjectURL(blob);

    // imgDest.onload = function() {
    // URL.revokeObjectURL(url);
    // this.ready();
    // };

    // imgDest.src = url;
    // });

    imgDest.src = canvas.toDataURL('image/jpeg');
    this.ready();
    }
    }