Skip to content

Instantly share code, notes, and snippets.

@DaxChen
Created March 28, 2016 03:59
Show Gist options
  • Save DaxChen/f7d9fc5684ad75505c25 to your computer and use it in GitHub Desktop.
Save DaxChen/f7d9fc5684ad75505c25 to your computer and use it in GitHub Desktop.
Cropping an image client-side using the Canvas
// 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