移动、PC图片拖拽缩放2

时间:2022-02-06 05:11:08

// 获取图片
function getImage() {
    let modal = document.getElementById("modal");
    getMainBox().addEventListener("click",function(e) { 
        let event = getEvent(e);
        let target = event.target || event.srcElement;

        if(isImage(target)) {
            let imgUrl = target.getAttribute("src");

            let str = `<img src="${imgUrl}" class="big-img" style="position: absolute; top: ${getImgInitPosition(target).top}px; left: ${getImgInitPosition(target).left}px; max-width: none; width: ${getImgInitPosition(target).width}px;cursor: move;" h="${getImgInitPosition(target).height}" w="${getImgInitPosition(target).width}"/>`;

            modal.innerHTML  = str;
            modal.style.display = "block";
            if(isMobile()) {
                zoomMobileImage()
            }
        }

    })

    modal.addEventListener("click", function(e) {
        let event = getEvent(e);
        let target = event.target || event.srcElement;
        if(isImage(target)) {
            if(!isMobile()) {
                zoomWebImage(target);
                drageWebImage();
            } 
        } else {
            this.style.display = "none"; 
        }
    })
}

function zoomWebImage(img) {
    img.addEventListener("mousewheel", function(e) {
        mouseScroll(this, getEvent(e));
    });
    img.addEventListener("DOMMouseScroll", function(e) {
        mouseScroll(this, getEvent(e));
    })
}

function mouseScroll(img, e) {
    var oper = Math.max(-1, Math.min(1,(e.wheelDelta || -e.originalEvent.detail)));
    var imgWidth = img.style.width;
    if(!!imgWidth) {
        imgWidth = parseInt(imgWidth);
        var newWidth = Math.max(640, Math.min(1920, imgWidth   (30*oper)));
        var left = parseInt(img.style.left) - (newWidth - imgWidth) / 2;

        img.style.width = newWidth   "px"; 
        img.style.left = left   "px";
    }
    
    adjustImgPosition(img);    
}

function zoomMobileImage() {
    let img = document.querySelector(".big-img");
    var startX, startY, scaleStartX, scaleStartY, imgHeight, imgWidth, initTop, initLeft, originalHeight, originalWidth;
    let initHeight = parseInt(img.getAttribute("h"));
    let initWidth = parseInt(img.getAttribute("w"));

    let initVal = 30;  // 防止图片拖出框内的最小边界值
    let clientHeight = document.body.clientHeight;
    let clientWidth = document.body.clientWidth;

    let boxWidthMin = initVal;
    let boxWidthMax = parseInt(clientWidth) - initVal;
    let boxHeightMin =  initVal;
    let boxHeightMax = parseInt(clientHeight) - initVal;

    img.addEventListener("touchstart", function(event) {
        preventDefaultEvt(event);
        let fingers = event.touches.length;  
        let touch1 = event.targetTouches[0];
        if(fingers === 2) {
            let touch2 = event.targetTouches[1]; 
            originalHeight = parseInt(window.getComputedStyle(img).height);
            originalWidth = parseInt(window.getComputedStyle(img).width);

            scaleStartX = Math.abs(touch1.clientX - touch2.clientX);
            scaleStartY = Math.abs(touch1.clientY - touch2.clientY);
        } else if(fingers === 1) {
            startX = touch1.clientX;
            startY = touch1.clientY;
            initTop = parseInt(img.style.top);
            initLeft= parseInt(img.style.left);
        }
    });

    img.addEventListener("touchmove", function(event) {
        preventDefaultEvt(event);
        let touch1 = event.targetTouches[0];
        let fingers = event.touches.length;  
        if (fingers === 2) {
            let touch2 = event.targetTouches[1]; 

            let scaleEndX = Math.abs(touch1.clientX - touch2.clientX);
            let scaleEndY = Math.abs(touch1.clientY - touch2.clientY);
            
            let scaleX = parseInt(scaleEndX) - parseInt(scaleStartX);
            let scaleY = parseInt(scaleEndY) - parseInt(scaleStartY);

            let width = scaleX   originalWidth;
            let height = scaleY   originalHeight; 

            if(width < initWidth || height < initHeight) {
                width = initWidth;
                height = initHeight;
                originalHeight = initHeight;
            }

            if(Math.abs(scaleX) > Math.abs(scaleY)) {
                img.style.width = width   "px";
            } else {
                img.style.width = (height / originalHeight) * width   "px";
            }

            adjustImgPosition(img);

        } else if(fingers === 1) {
            let clientX = touch1.clientX;
            let clientY = touch1.clientY;

            if(clientY >= boxHeightMin && clientY <= boxHeightMax) {
                img.style.top = initTop   clientY - startY   "px";
            } 

            if(clientX >= boxWidthMin && clientX <= boxWidthMax) {
                img.style.left = initLeft   clientX - startX   "px";
            }
        }
    });
}

function getImgInitPosition(img) {
    let clientHeight = document.body.clientHeight;
    let clientWidth = document.body.clientWidth;
    let width = isMobile() ? 340 : 640;
    let imgHeight = window.getComputedStyle(img).height;

    return {
        top: (parseInt(clientHeight) - parseInt(imgHeight)) / 2,
        left: (parseInt(clientWidth) - width) / 2,
        width: parseInt(width),
        height: parseInt(imgHeight)
    };
}

function adjustImgPosition(img) {
    let clientHeight = document.body.clientHeight;
    let clientWidth = document.body.clientWidth;
    let imgHeight = window.getComputedStyle(img).height;
    let imgWidth = window.getComputedStyle(img).width;

    if(!!clientHeight) {
        var top = (parseInt(clientHeight) - parseInt(imgHeight)) / 2;
        var left = (parseInt(clientWidth) - parseInt(imgWidth)) / 2;
        img.style.top = top   ‘px‘;
        img.style.left = left   ‘px‘;
    }
} 

function isMobile() {
    return !!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i));
}

function getEvent(e) {
    return e || window.event;
}

function drageWebImage() {
    (function() {
        var isDrag = false;
        var dragTarget;
        var startX, startY;
        var imgPositionTop,imgPositionLeft;
        var boxWidthMin, boxWidthMax, boxHeightMin, boxHeightMax;

        function initDrag(e) {
            let event = getEvent(e);
            let dragHandle = event.target || event.srcElement;
            var topElement = "HTML";
            
            var eventBtn = event.button == 0 || event.button == 1

            if(isMobile()) {
                eventBtn = true;
            }

            while (dragHandle.tagName != topElement && dragHandle.className != "big-img") {
                dragHandle = dragHandle.parentElement;
                
            }
            
            if (dragHandle.className == "big-img" && eventBtn) {
                isDrag = true;
                dragTarget = dragHandle;

                imgPositionTop = parseInt(dragTarget.style.top);
                startY = event.clientY || event.pageY;
                imgPositionLeft = parseInt(dragTarget.style.left);
                startX = event.clientX || event.pageX;

                let initVal = 50;  // 防止图片拖出框内的最小边界值
                let clientHeight = document.body.clientHeight;
                let clientWidth = document.body.clientWidth;

                boxWidthMin = initVal;
                boxWidthMax = parseInt(clientWidth) - initVal;
                boxHeightMin =  initVal;
                boxHeightMax = parseInt(clientHeight) - initVal;

                document.addEventListener("mousemove", moveMouse)
                return false;
            }

            function moveMouse(e) {
                let event = getEvent(e);
                if (isDrag) {
                    var clientY = event.clientY;
                    var clientX = event.clientX;

                    if(clientY >= boxHeightMin && clientY <= boxHeightMax) {
                        dragTarget.style.top = imgPositionTop   clientY - startY   "px";
                    }
                    if(clientX >= boxWidthMin && clientX <= boxWidthMax) {
                        dragTarget.style.left = imgPositionLeft   clientX - startX   "px";
                    }
                    return false;
                }
            }
        }

        document.addEventListener("mousedown", initDrag)
        document.addEventListener("mouseup", function() {
            isDrag = false;
        })
    })();
}

function preventDefaultEvt(event) {
    if(event && event.preventDefault) {
        event.preventDefault();
    } else {
        window.event.returnValue = false;
        return false
    }
}



getImage();