From 8e7a09f3f30e7609a8ae58f9e37446e0a1245604 Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Mon, 23 Nov 2020 18:13:38 +0100 Subject: [PATCH] Initial version of crop boundary dragging. --- public/js/crop_editor.js | 47 +++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/public/js/crop_editor.js b/public/js/crop_editor.js index 770445a..92c4caf 100644 --- a/public/js/crop_editor.js +++ b/public/js/crop_editor.js @@ -187,16 +187,19 @@ class CropEditor { addEvents(event) { let drag_target = this.image_container; - drag_target.addEventListener('mousedown', this.dragStart); - drag_target.addEventListener('mousemove', this.drag); - drag_target.addEventListener('mouseup', this.dragEnd); - drag_target.addEventListener('mouseout', this.dragEnd); + drag_target.addEventListener('mousedown', this.dragStart.bind(this)); + drag_target.addEventListener('mousemove', this.drag.bind(this)); + drag_target.addEventListener('mouseup', this.dragEnd.bind(this)); + // drag_target.addEventListener('mouseout', this.dragEnd.bind(this)); this.original_image.addEventListener('mousedown', event => {return false}); + this.original_image.addEventListener('dragstart', event => {return false}); } dragStart(event) { this.isDragging = true; + this.dragStartX = event.pageX - event.target.offsetLeft; + this.dragStartY = event.pageY - event.target.offsetTop; console.log(`Start @ x=${event.pageX}, y=${event.pageY}, which=${event.which}`); } @@ -206,13 +209,47 @@ class CropEditor { } this.isDragging = false; console.log(`End @ x=${event.pageX}, y=${event.pageY}, which=${event.which}`); + this.handleDragEvent(event); } drag(event) { if (!this.isDragging) { return; } - console.log(`Drag @ x=${event.pageX}, y=${event.pageY}, which=${event.which}`); + // console.log(`Drag @ x=${event.pageX}, y=${event.pageY}, which=${event.which}`); + this.handleDragEvent(event); + } + + getScaleFactor() { + let real_width = this.original_image.naturalWidth, + real_height = this.original_image.naturalHeight, + scaled_width = this.original_image.clientWidth, + scaled_height = this.original_image.clientHeight; + + return scaled_width / real_width; + } + + handleDragEvent(event) { + if (!this.isDragging) { + return; + } + + let curX = event.pageX - event.target.offsetLeft, + curY = event.pageY - event.target.offsetTop; + + this.dragEndX = Math.max(curX, this.dragStartX); + this.dragEndY = Math.max(curY, this.dragStartY); + this.dragStartX = Math.min(curX, this.dragStartX); + this.dragStartY = Math.min(curY, this.dragStartY); + + let scaleFactor = this.getScaleFactor(); + + this.source_x.value = this.dragStartX; + this.source_y.value = this.dragStartY; + this.crop_width.value = Math.ceil(this.dragEndX / scaleFactor); + this.crop_height.value = Math.ceil(this.dragEndY / scaleFactor); + + this.positionBoundary(); } toggleCropButton() {