Координаты щелчка после преобразования CSS: масштаб - PullRequest
0 голосов
/ 18 декабря 2018

Я играю с изменяющим размеры изображения, у меня есть, чтобы вы могли выбрать размеры для изменения размера, например, 1920x1080, затем вы можете перетаскивать ваше изображение внутри этих размеров, как в Photoshop, если вы хотите обрезать или изменить размер изображения, явстроенное «масштабирование», в котором можно масштабировать рабочее пространство, масштабирование просто выполняется с помощью CSS, наполовину уменьшая размеры нашего «рабочего пространства» и используя transform: scale ()

Сейчас только верхний левыйhandle работает для изменения размера и отлично работает при использовании шкалы 1, если вы измените масштаб на 0,5 (строка 9) и повторите попытку, вы увидите, что в мышах X & Y есть неправильный расчет, если вы посмотрите на строку 88демо - это то, где X и Y для поля изображения устанавливаются при изменении размера, я знаю, что это число нужно как-то масштабировать, хотя я даже не уверен, с чего начать при математическом разборе этой проблемы

https://codepen.io/anon/pen/XojMZB

class Cropper {
constructor() {
    this.css_class = {
        loading: 'loading'
    };
    this.default_scale = 1; //eg: 0.5 = 50% or 0.25 = 25%
    this.current_scale = null;
    this.crop_width = 1920;
    this.crop_height = 1080;
    this.metric_pixel = 'px';
    this.metric_scheme = this.metric_pixel;
    this.callbacks = {};
    // this.is_dragging_image = false;
    this.loading = true;
    this.resize_acceleration = 2;
    this.image_pos = {
        width: 0,
        height: 0,
        currentX: 0,
        currentY: 0,
        initialX: 0,
        initialY: 0,
        offsetX: 0,
        offsetY: 0,
    };
    this.resize_state = {};
    this.registerElements();

    /**
     *  Start up when our image has been loaded
     **/
    this.cropper_target_image.onload = () => {
        this.init();
    };
}
getCanvasScale() {
    return this.current_scale || this.default_scale
}
getCanvasScaleCalc() {
    return (1 / this.getCanvasScale())
}
getCanvasWidth(metric = true) {
    let scheme = (metric) ? this.metric_scheme : 0;
    return (this.crop_width / this.getCanvasScaleCalc()) + scheme
}
getCanvasHeight(metric = true) {
    let scheme = (metric) ? this.metric_scheme : 0;
    return (this.crop_height / this.getCanvasScaleCalc()) + scheme
}
getNaturalImageWidth(metric = true) {
    let scheme = (metric) ? this.metric_pixel : 0;
    return this.cropper_target_image.naturalWidth + scheme
}
getNaturalImageHeight(metric = true) {
    let scheme = (metric) ? this.metric_pixel : 0;
    return this.cropper_target_image.naturalHeight + scheme
}

//Image manipulation
moveImage(x, y) {
    // this.resize_state.container_left = x;
    // this.resize_state.container_top = y;
    this.cropper_image_dragger.style.transform = `translate3d(${ x }px, ${ y }px, 0)`;
}

//Resize Events
resizeBegin(mouseEvent) {
    mouseEvent.preventDefault();
    mouseEvent.stopPropagation();
    this.saveMouseState(mouseEvent);
    document.addEventListener('mousemove', this, true);
    document.addEventListener('mouseup', this, true);
}

resizing(mouseEvent) {
    let mouse = {},
        width, height, left, top, constrain = false;
    mouse.x = (mouseEvent.clientX);
    mouse.y = (mouseEvent.clientY);

    if (this.resize_state.click_target === this.resize_anchors.top_left) {
        width = (this.resize_state.container_width) - (mouse.x - this.resize_state.container_left);
        height = (this.resize_state.container_height) - (mouse.y - this.resize_state.container_top);

        left = (mouse.x);
        top = (mouse.y);
        // if(constrain || mouseEvent.shiftKey){
        //     top = mouse.y - ((width / this.getNaturalImageWidth(false) * this.getNaturalImageHeight(false)) - height);
        // }
    }
    this.resizeImage(width, height);
    this.moveImage(left, top);
    // this.saveMouseState(mouseEvent);
}
endResize(mouseEvent) {
    mouseEvent.preventDefault();
    this.saveMouseState(mouseEvent);
    document.removeEventListener('mousemove', this, true);
    document.removeEventListener('mouseup', this, true);
}
resizeImage(width, height) {
    this.cropper_image_dragger.style.width = width + 'px';
    this.cropper_image_container.style.width = width + 'px';
    this.cropper_image_dragger.style.height = height + 'px';
    this.cropper_image_container.style.height = height + 'px'
};
saveMouseState(mouseEvent) {
    // Save the initial event details and container state
    let drag_pos = this.cropper_image_dragger.getBoundingClientRect();

    this.resize_state.container_width = this.cropper_image_dragger.offsetWidth;
    this.resize_state.container_height = this.cropper_image_dragger.offsetHeight;
    this.resize_state.container_left = drag_pos.left;
    this.resize_state.container_top = drag_pos.top;
    this.resize_state.mouse_x = (mouseEvent.clientX || mouseEvent.pageX || mouseEvent.touches[0].clientX); // + window.pageXOffset
    this.resize_state.mouse_y = (mouseEvent.clientY || mouseEvent.pageY || mouseEvent.touches[0].clientY); // + window.pageYOffset
    this.resize_state.click_target = mouseEvent.target;

    if (mouseEvent.touches) {
        this.resize_state.touches = [];

        [].forEach.call(mouseEvent.touches, function(i, ob) {
            this.resize_state.touches[i] = {};
            this.resize_state.touches[i].clientX = 0 + ob.clientX;
            this.resize_state.touches[i].clientY = 0 + ob.clientY;
        });
    }
    this.resize_state.evnt = mouseEvent
}

//init
registerElements() {
    this.cropper_wrapper = document.getElementById('cropper-wrap');
    this.cropper_wrapper.classList.add(this.css_class.loading);

    this.cropper_container = document.getElementById('cropper-container');
    this.cropper_true_dimension = document.getElementById('true-dimension');
    this.cropper_true_anchor = document.getElementById('true-anchor');
    this.cropper_image_dragger = document.getElementById('the-image-dragger');
    this.cropper_image_container = document.getElementById('the-image-container');
    this.cropper_target_image = document.getElementById('cropper-target-image');
    this.resize_anchors_wrap = document.getElementById('resize-anchors');
    let resize_anchors = this.resize_anchors_wrap.getElementsByClassName('resize-anchor');
    this.resize_anchors = {
        top_left: resize_anchors[0],
        top_right: resize_anchors[1],
        bottom_left: resize_anchors[2],
        bottom_right: resize_anchors[3]
    };
}
removeResize() {
    this.resize_anchors_wrap.removeEventListener("mousedown", this, false);
}
registerEvents() {
    this.resize_anchors_wrap.addEventListener("mousedown", this, false);
    this.resize_anchors_wrap.addEventListener("mouseup", this, false);
}
init() {
    this.registerEvents();

    //wrapper
    this.cropper_container.style.width = this.getCanvasWidth();
    this.cropper_container.style.height = this.getCanvasHeight();
    this.cropper_container.style.margin = 'auto';

    //Setup True Dimension Elements
    this.cropper_true_dimension.style.transform = `scale(${ this.getCanvasScale() })`;
    this.cropper_true_dimension.style.width = this.crop_width + this.metric_scheme;
    this.cropper_true_dimension.style.height = this.crop_height + this.metric_scheme;

    //anchor
    this.cropper_true_anchor.style.width = this.crop_width + this.metric_scheme;
    this.cropper_true_anchor.style.height = this.crop_height + this.metric_scheme;

    this.cropper_image_dragger.style.width = this.getNaturalImageWidth();
    this.cropper_image_dragger.style.height = this.getNaturalImageHeight();

    this.cropper_image_container.style.width = this.getNaturalImageWidth();
    this.cropper_image_container.style.height = this.getNaturalImageHeight();

    let init_image_x = this.getCanvasWidth(false) - (this.getNaturalImageWidth(false) / this.getCanvasScaleCalc());
    let init_image_y = this.getCanvasHeight(false) - (this.getNaturalImageHeight(false) / this.getCanvasScaleCalc());

    this.moveImage(init_image_x, init_image_y);
    this.image_pos = {
        width: this.getNaturalImageWidth(false),
        height: this.getNaturalImageHeight(false),
        //position on canvas
        currentX: init_image_x,
        currentY: init_image_y,
        initialX: init_image_x,
        initialY: init_image_y,
        offsetX: init_image_x / 2,
        offsetY: init_image_y / 2,
    };
    this.moveImage(0, 0);
    this.loading = false;
    this.cropper_wrapper.classList.remove(this.css_class.loading);
    return true;
}

handleEvent(event) {
    switch (event.type) {
        //This is just used for listeners you will need to trash throughout lifecycle
        //ps. The drag events live forever so they're outside of this built-in listener that we only use for trashing purposes
        case "mousedown":
            this.resizeBegin(event);
            break;
        case "mousemove":
            this.resizing(event);
            break;
        case "mouseup":
            this.endResize(event);
            break;
        default:
            return console.warn(this.constructor.name + '.handleEvent could not find a matching event type');
    }
}}let cropper = new Cropper();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...