From 5c4a075231a106f5876a58ea5dcb80ad67eeddb2 Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Wed, 30 Dec 2020 12:56:17 +0100 Subject: [PATCH] Constrain aspect ratio conservation to image boundaries as well. --- public/js/crop_editor.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/public/js/crop_editor.js b/public/js/crop_editor.js index cc005993..555ec832 100644 --- a/public/js/crop_editor.js +++ b/public/js/crop_editor.js @@ -292,10 +292,23 @@ class CropEditor { let targetAspectRatio = current.crop_width / current.crop_height; if (Math.abs(currentAspectRatio - targetAspectRatio) > 0.001) { + // Landscape? if (targetAspectRatio > 1.0) { - this.crop_height.value = Math.ceil(this.crop_width.value / targetAspectRatio); - } else { - this.crop_width.value = Math.ceil(this.crop_height.value * targetAspectRatio); + let height = Math.ceil(this.crop_width.value / targetAspectRatio); + if (parseInt(this.source_y.value) + height > this.original_image.naturalHeight) { + height = this.original_image.naturalHeight - this.source_y.value; + } + this.crop_width.value = height * targetAspectRatio; + this.crop_height.value = height; + } + // Portrait? + else { + let width = Math.ceil(this.crop_height.value * targetAspectRatio); + if (parseInt(this.source_x.value) + width > this.original_image.naturalWidth) { + width = this.original_image.naturalWidth - this.source_x.value; + } + this.crop_width.value = width; + this.crop_height.value = width / targetAspectRatio; } } }