Please review for readability.
/*
Takes a screenshot of the current tab, then scales it to width and height.
Returns null if the tab is smaller than width and height.
Crops the screenshot to maintain aspect ratio.
Also crops the screenshot to avoid scaling down by more maximumScaleFactor.
*/
var GetCurrentScreenshot = function (width, height, maximumScaleFactor) {
return new RSVP.Promise(function (resolve) {
chrome.tabs.captureVisibleTab(null, { format: 'png' }, function (dataURL) {
var sourceImage = new Image();
sourceImage.onload = function () {
var canvas = document.createElement("canvas");
var cropWidth = sourceImage.width;
var cropHeight = sourceImage.height;
if (cropWidth < width || cropHeight < height) {
resolve(null);
return;
}
var outputRatio = width / height;
var inputRatio = cropWidth / cropHeight;
if (outputRatio > inputRatio) {
cropHeight = cropWidth / outputRatio;
} else {
cropWidth = cropHeight * outputRatio;
}
//This should be impossible
if (cropWidth > sourceImage.width) cropWidth = sourceImage.width;
if (cropHeight > sourceImage.height) cropHeight = sourceImage.height;
if (cropWidth > width * maximumScaleFactor) {
cropHeight = cropHeight / (cropWidth / (width * maximumScaleFactor));
cropWidth = width * maximumScaleFactor;
}
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(sourceImage, 0, 0, cropWidth,
cropHeight, 0, 0, width, height);
resolve(canvas.toDataURL());
};
sourceImage.src = dataURL;
});
});
};