smartcrop-browser
Version:
smartcrop package for browser
59 lines (50 loc) • 2.36 kB
JavaScript
const smartcrop = require("smartcrop");
var smartcropBrowser = function () {};
smartcropBrowser.prototype = {
constructor: smartcropBrowser,
/**
* Give crop coordinates which can be used for crop preview **WONT WORK IN NODE, ONLY IN BROWSER**
* @param {object} image_data Base64 image data with height and width {file:"base64",width:"number",height:"number"}
* @param {number} crop_container_width the image container's width
* @param {number} minScale used for scaling image in crop
* @param {number} zoom Base64 image data
* @returns crop and zoom parameters which can be passed to utilities like react-easy-crop
*/
cropImage: async function (image_data, crop_container_width, minScale, zoom) {
try {
let image = new Image();
image.src = image_data.file;
const imageWidth = image_data.width;
const imageHeight = image_data.height;
// Require an image object
const crop_coordinates = await smartcrop
.crop(image, {
width: 100,
height: 100,
ruleOfThirds: true,
minScale: minScale || 0.5,
})
.then(function (result) {
// Input image is resized to fit the crop_container_width
const cropOuterContainerSide = crop_container_width || 464;
// Normalised crop points for the new container side
let normalisedCropX = (cropOuterContainerSide * result.topCrop.x) / imageWidth;
let normalisedCropY = (cropOuterContainerSide * result.topCrop.y) / imageHeight;
// The side of area which user can move to crop the image
let cropInnerContainerSide = (imageHeight * cropOuterContainerSide) / imageWidth;
let cropHalf = (cropOuterContainerSide - cropInnerContainerSide) / 0.8999;
let cropHalfY = (cropOuterContainerSide - cropInnerContainerSide) / 2;
let canvas_x = cropHalf - normalisedCropX;
let canvas_y = cropHalfY - normalisedCropY;
return { canvas_x: canvas_x, canvas_y: canvas_y, zoom: zoom || 1.2 };
});
return crop_coordinates;
} catch (error) {
console.log("smartcropBrowser [cropImage] failed", {
error: error,
});
}
},
};
var smartcropBrowser = new smartcropBrowser();
module.exports = smartcropBrowser;