When the picture is cropped, the box is lost when following the mouse.

as shown in the figure above, the dashed frame in the figure is the div element that needs to follow the mouse movement. The div element following the mouse movement has been implemented, but if the mouse moves too fast, the div element will not keep up. How to optimize this problem?

all code can visit github to get

part of the implementation code is as follows:

    let selector = document.getElementById("selector");// 
    let moveStartPoint = {x: 0, y: 0};// 
    let selectorLocation = {x: 150, y: 150};// 
    selector.onmousedown = function (event) {
        moveStartPoint.x = event.clientX;
        moveStartPoint.y = event.clientY;
        selectorLocation.x = selector.offsetLeft;
        selectorLocation.y = selector.offsetTop;
    };

    selector.onmousemove = function (event) {
        compute();
    };

    function compute() {
        if (movable) {
            let leftLocation = event.clientX - moveStartPoint.x + selectorLocation.x;
            let topLocation = event.clientY - moveStartPoint.y + selectorLocation.y;
            // 
            if (leftLocation <= 0 || leftLocation >= 298) {
                if (leftLocation <= 0) {
                    leftLocation = 0;
                } else {
                    leftLocation = 298;
                }
            }
            if (topLocation <= 0 || topLocation >= 298) {
                if (topLocation <= 0) {
                    topLocation = 0;
                } else {
                    topLocation = 298;
                }
            }
            selector.style.left = leftLocation + "px";
            selector.style.top = topLocation + "px";
        }
    }
Jun.23,2021
Menu