Created
March 28, 2016 03:59
-
-
Save DaxChen/f7d9fc5684ad75505c25 to your computer and use it in GitHub Desktop.
Cropping an image client-side using the Canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From README of: https://github.com/DominicTobias/react-image-crop | |
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment