From 66a411973a075ba72f26dbd851e7fdae2f5d9222 Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Thu, 17 Dec 2020 13:05:24 +0100 Subject: [PATCH] Constrain crop proportions by default, with checkbox to disable. --- public/css/admin.css | 7 +++---- public/js/crop_editor.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/public/css/admin.css b/public/css/admin.css index 34a56b4e..d1db4e54 100644 --- a/public/css/admin.css +++ b/public/css/admin.css @@ -156,14 +156,13 @@ body { z-index: 100; color: #fff; } -#crop_editor input { +#crop_editor input[type=number] { width: 50px; background: #555; color: #fff; } -.crop_image_container { - position: relative; - flex-grow: 1; +#crop_editor input[type=checkbox] { + vertical-align: middle; } .crop_position { background: rgba(0, 0, 0, 1.0); diff --git a/public/js/crop_editor.js b/public/js/crop_editor.js index 53488f0e..cc005993 100644 --- a/public/js/crop_editor.js +++ b/public/js/crop_editor.js @@ -66,6 +66,17 @@ class CropEditor { this.crop_height.addEventListener("keyup", this.positionBoundary.bind(this)); this.position.appendChild(this.crop_height); + this.crop_constrain_label = document.createElement("label"); + this.position.appendChild(this.crop_constrain_label); + + this.crop_constrain = document.createElement("input"); + this.crop_constrain.checked = true; + this.crop_constrain.type = 'checkbox'; + this.crop_constrain_label.appendChild(this.crop_constrain); + + this.crop_constrain_text = document.createTextNode('Constrain proportions'); + this.crop_constrain_label.appendChild(this.crop_constrain_text); + this.save_button = document.createElement("span"); this.save_button.className = "btn"; this.save_button.textContent = "Save"; @@ -159,6 +170,8 @@ class CropEditor { this.crop_height.max = source.naturalHeight; this.source_x.max = source.naturalWidth - 1; this.source_y.max = source.naturalHeight - 1; + + this.crop_constrain_text.textContent = `Constrain proportions (${current.crop_width} × ${current.crop_height})`; } showContainer() { @@ -272,6 +285,21 @@ class CropEditor { let height = Math.ceil(Math.abs(this.dragEndY - this.dragStartY) * scaleFactor); this.crop_height.value = Math.min(height, this.original_image.naturalHeight - this.source_y.value); + if (this.crop_constrain.checked) { + let current = this.thumbnail_select.options[this.thumbnail_select.selectedIndex].dataset; + + let currentAspectRatio = parseInt(this.crop_width.value) / parseInt(this.crop_height.value); + let targetAspectRatio = current.crop_width / current.crop_height; + + if (Math.abs(currentAspectRatio - targetAspectRatio) > 0.001) { + 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); + } + } + } + this.positionBoundary(); }