原生js实现图片预览控件,支持丝滑拖拽,滚轮放缩,放缩聚焦

手撸源代码如下:注释应该很详细了,拿去直用

可以放到在线编辑器测试,记得修改图片路径

菜鸟教程在线编辑器

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #img_box {
            position: relative;
            width: 800px;
            height: 800px;
            border: 1px solid #000000;
            overflow: hidden;
            cursor: grab;
        }

        #img_c {
            width: 100%;
            height: 100%;
            position: absolute;
            object-fit: contain;
            user-select: none;
            -webkit-user-drag: none;
            user-select: none;
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            /* transition: all 0.1s ease-in-out; */
        }
    </style>
</head>

<body>
    <div id="img_box">
        <img id="img_c" title="没有" src="./1719194464803.jpg">
    </div>
    <script>
        initImageScaleElement();
        function initImageScaleElement() {
            //定义参数
            const max = 20;//放缩原图倍数
            const scale = 0.05;//滚轮一下缩放的变化比例 越大放缩越快

            //获取对象
            const box = document.getElementById("img_box");
            const img = document.getElementById("img_c");

            /**
             * 图片已加载完毕后,对图片居中
             * 图片一开始其实默认是居中的,只不过是img的object-fit: contain属性进行了居中,并且产生了一些边缘填充空白
             * 这些填充的空白会影响后续图片拖拽的计算,因此需要将img修改成图片展示的真实大小,但对用户视觉不发生改变。
             */
            img.onload = function () {
                const imgRatio = img.naturalWidth / img.naturalHeight; //图片横纵比
                const boxRatio = box.clientWidth / box.clientHeight;   //容器横纵比
                /**
                 * 因为拿到的图片真实大小,不是显示大小,需要手动放缩,适配到容器中
                 * 当图片横纵比大于容器横纵比,图片保持比例的情况下填充容器,此时只能对图片的横向放缩填充全部容器 
                 * 当图片横纵比小于容器横纵比,图片保持比例的情况下填充容器,此时只能对图片的纵向放缩填充全部容器 
                 * 这个规律可以自己画图试验一下
                 */
                if (imgRatio > boxRatio) { 
                    const scale = box.clientWidth / img.naturalWidth;
                    img.style.width = box.clientWidth; //长度填充
                    img.style.height = img.naturalHeight * scale; //高度自适应
                    img.style.top = Math.ceil((box.clientHeight - img.clientHeight) / 2) + "px" ;//位置居中
                } else {
                    const scale = box.clientHeight / img.naturalHeight;
                    img.style.height = box.clientHeight;//高度填充
                    img.style.width = img.naturalWidth * scale;//长度自适应
                    img.style.left = Math.ceil((box.clientWidth - img.clientWidth) / 2) + "px";//位置居中
                }
            };
            //用于元素拖拽时边界的参数限制,入参:{ 实际值,左区间,右区间 }
            const getRange = (actual, limita, limitb) => {
                if (actual < -limita) {
                    return -limita;
                } else if (actual > limitb) {
                    return limitb;
                }
                return actual;
            }
            /**
             * 缩放操作
             * 
             */
            box.onwheel = (event) => {
                event.preventDefault(); //关闭默认事件
                const center_x = event.clientX;
                const center_y = event.clientY;
                const wheelDelta = event.deltaY;
                const top_d = center_y - img.offsetTop;
                const left_d = center_x - img.offsetLeft;
                if (wheelDelta > 0) {//缩小 往后推滚轮  【滚轮值和缩放关系不是固定的,你也可以反过来】
                    let modifyHeight = img.clientHeight * (1 - scale);
                    let modifyWidth = img.clientWidth * (1 - scale);
                    if (modifyHeight * max > img.naturalHeight) { //只在比例范围内,放缩
                        img.style.height = modifyHeight;
                        img.style.width = modifyWidth;
                        img.style.top = center_y - top_d * (1 - scale);
                        img.style.left = center_x - left_d * (1 - scale);
                    } else {
                        console.log("缩小超出" + max * 100 + "%比例无法缩小");
                    }
                } else {//放大  往前推滚轮
                    let modifyHeight = img.clientHeight * (1 + scale);
                    let modifyWidth = img.clientWidth * (1 + scale);
                    if (modifyHeight < img.naturalHeight * max) { //只在比例范围内,放缩
                        img.style.height = modifyHeight;
                        img.style.width = modifyWidth;
                        img.style.top = center_y - top_d * (1 + scale);
                        img.style.left = center_x - left_d * (1 + scale);
                    } else {
                        console.log("放大超出" + max * 100 + "%比例无法放大");
                    }
                }
            }
            
            /**
             * 拖拽操作
             */
            //拖拽需要的全局变量
            const drag = {
                status: false,
                lastX: null,
                lastY: null
            }
            box.onmousedown = (event) => {
                if (event.button === 0) {
                    //鼠标会移出元素,甚至移出到浏览器外部,使用document监听移动就可以不受影响。
                    document.onmousemove = (event) => {
                        if (drag.status) {
                            let mx = event.clientX - drag.lastX
                            let my = event.clientY - drag.lastY
                            drag.lastX = event.clientX
                            drag.lastY = event.clientY
                            let top = img.offsetTop + my
                            let left = img.offsetLeft + mx
                            //拖拽超出容器外部无意义,可能找不回,因此图片位置不能任意拖拽至少有一个角或一个边在容器内部,这里减10就是预留出的宽度
                            img.style.left = getRange(left, img.clientWidth - 10, box.clientWidth - 10) + 'px';
                            img.style.top = getRange(top, img.clientHeight - 10, box.clientHeight - 10) + "px";
                            //如果你不想让图片跑出容器,那就调整这里就好了,控制两个相邻边就能控制整个图片,如
                            // img.style.left = getRange(left,0, box.clientWidth - img.clientWidth) + 'px';
                            // img.style.top = getRange(top,0, box.clientHeight - img.clientHeight) + "px";
                        }
                    }
                    //鼠标松开,初始化操作,如果鼠标在元素外部松开,元素的松开监听是获取不到的,因此需要用document监听
                    document.onmouseup = (event) => {
                        if (event.button === 0) {
                            drag.status = false
                            document.onmousemove = null
                            document.onmouseup = null
                        }
                    }
                    drag.status = true
                    drag.lastX = event.clientX
                    drag.lastY = event.clientY
                }
            }
        }
    </script>

</body>

</html>

 进阶版

这样使用还是很不方便,于是浓缩成一个函数,传入url便可直接预览

/**
* 图片预览函数,调用后自动预览图片
* @param {图片地址} imgurl 
*/
function openImagePreview(imgurl) {
    if (!imgurl) return;
    //定义参数
    const max = 20;//放缩原图倍数
    const scale = 0.05;//滚轮一下缩放的变化比例 越大放缩越快
 
    //定义对象
    const box = document.createElement("div");
    // box.style.cssText = "position: fixed;top:0px;left:0px;z-index: 10000;background-color: rgba(0,0, 0, 0.3);width:" + (document.documentElement.clientWidth) + "px;height:" + (document.documentElement.clientHeight) + "px;overflow: hidden;cursor: grab;";
    box.style.cssText = "position: fixed;top:0px;left:0px;z-index: 10000;background-color: rgba(0,0, 0, 0.3);width:100%;height:100%;overflow: hidden;cursor: grab;";
    const img = document.createElement("img");
    img.style.cssText = "position: absolute;object-fit: contain;user-select: none;-webkit-user-drag: none;user-select: none;-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;";
    img.src = imgurl;
    img.title = "预览";
    const close = document.createElement("div");
    close.innerHTML =`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" font-size="20" class="iconify iconify--gitee icon-xmark" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 16 16"><g fill="none" fill-rule="evenodd"><path d="M0 0h16v16H0z"></path><path fill="currentColor" d="M13.303 2.697a.5.5 0 010 .707L8.707 8l4.596 4.596a.5.5 0 01-.707.707L8 8.707l-4.596 4.596a.5.5 0 01-.707-.707L7.293 8 2.697 3.404a.5.5 0 01.707-.707L8 7.293l4.596-4.596a.5.5 0 01.707 0z"></path></g></svg>`;
    close.style.cssText = "position: absolute;top:20px;right:20px;align-items: center;color:white;display: flex;justify-content: center;background: rgba(29,29,37,0.4);border-radius: 50%;width:30px;height:30px;";
    close.onclick = () => {
        document.body.removeChild(box);
    }
    box.append(img);
    box.append(close);
    document.body.append(box);
 
    /**
     * 图片已加载完毕后,对图片居中
     * 图片一开始其实默认是居中的,只不过是img的object-fit: contain属性进行了居中,并且产生了一些边缘填充空白
     * 这些填充的空白会影响后续图片拖拽的计算,因此需要将img修改成图片展示的真实大小,但对用户视觉不发生改变。
     */
    img.onload = function () {
        const imgRatio = img.naturalWidth / img.naturalHeight; //图片横纵比
        const boxRatio = box.clientWidth / box.clientHeight;   //容器横纵比
        /**
         * 因为拿到的图片真实大小,不是显示大小,需要手动放缩,适配到容器中
         * 当图片横纵比大于容器横纵比,图片保持比例的情况下填充容器,此时只能对图片的横向放缩填充全部容器 
         * 当图片横纵比小于容器横纵比,图片保持比例的情况下填充容器,此时只能对图片的纵向放缩填充全部容器 
         * 这个规律可以自己画图试验一下
         */
        if (imgRatio > boxRatio) {
            const scale = box.clientWidth / img.naturalWidth;
            img.style.width = box.clientWidth+"px"; //长度填充
            img.style.height = img.naturalHeight * scale+"px"; //高度自适应
            img.style.top = Math.ceil((box.clientHeight - img.clientHeight) / 2) + "px";//位置居中
        } else {
            const scale = box.clientHeight / img.naturalHeight;
            img.style.height = box.clientHeight+"px";//高度填充
            img.style.width = img.naturalWidth * scale+"px";//长度自适应
            img.style.left = Math.ceil((box.clientWidth - img.clientWidth) / 2) + "px";//位置居中
        }
    };
    //用于元素拖拽时边界的参数限制,入参:{ 实际值,左区间,右区间 }
    const getRange = (actual, limita, limitb) => {
        if (actual < -limita) {
            return -limita;
        } else if (actual > limitb) {
            return limitb;
        }
        return actual;
    }
    /**
     * 缩放操作
     * 
     */
    box.onwheel = (event) => {
        console.log(event)
        event.preventDefault(); //关闭默认事件
        const center_x = event.clientX;
        const center_y = event.clientY;
        const wheelDelta = event.deltaY;
        const top_d = center_y - img.offsetTop;
        const left_d = center_x - img.offsetLeft;
        if (wheelDelta > 0) {//缩小 往后推滚轮  【滚轮值和缩放关系不是固定的,你也可以反过来】
            let modifyHeight = img.clientHeight * (1 - scale);
            let modifyWidth = img.clientWidth * (1 - scale);
            if (modifyHeight * max > img.naturalHeight) { //只在比例范围内,放缩
                img.style.height = modifyHeight+"px";
                img.style.width = modifyWidth+"px";
                img.style.top = (center_y - top_d * (1 - scale))+"px";
                img.style.left = (center_x - left_d * (1 - scale))+"px";
            } else {
                console.log("缩小超出" + max * 100 + "%比例无法缩小");
            }
        } else {//放大  往前推滚轮
            let modifyHeight = img.clientHeight * (1 + scale);
            let modifyWidth = img.clientWidth * (1 + scale);
            if (modifyHeight < img.naturalHeight * max) { //只在比例范围内,放缩
                img.style.height = modifyHeight+"px";
                img.style.width = modifyWidth+"px";
                img.style.top = (center_y - top_d * (1 + scale))+"px";
                img.style.left = (center_x - left_d * (1 + scale))+"px";
            } else {
                console.log("放大超出" + max * 100 + "%比例无法放大");
            }
        }
    }
 
    /**
     * 拖拽操作
     */
    //拖拽需要的全局变量
    const drag = {
        status: false,
        lastX: null,
        lastY: null
    }
    box.onmousedown = (event) => {
        document.body.style.userSelect = 'none';
        if (event.button === 0) {
            //鼠标会移出元素,甚至移出到浏览器外部,使用document监听移动就可以不受影响。
            document.onmousemove = (event) => {
                if (drag.status) {
                    let mx = event.clientX - drag.lastX
                    let my = event.clientY - drag.lastY
                    drag.lastX = event.clientX
                    drag.lastY = event.clientY
                    let top = img.offsetTop + my
                    let left = img.offsetLeft + mx
                    //拖拽超出容器外部无意义,可能找不回,因此图片位置不能任意拖拽至少有一个角或一个边在容器内部,这里减10就是预留出的宽度
                    img.style.left = getRange(left, img.clientWidth - 10, box.clientWidth - 10) + 'px';
                    img.style.top = getRange(top, img.clientHeight - 10, box.clientHeight - 10) + "px";
                    //如果你不想让图片跑出容器,那就调整这里就好了,控制两个相邻边就能控制整个图片,如
                    // img.style.left = getRange(left,0, box.clientWidth - img.clientWidth) + 'px';
                    // img.style.top = getRange(top,0, box.clientHeight - img.clientHeight) + "px";
                }
            }
            //鼠标松开,初始化操作,如果鼠标在元素外部松开,元素的松开监听是获取不到的,因此需要用document监听
            document.onmouseup = (event) => {
                document.body.style.userSelect = '';
                if (event.button === 0) {
                    drag.status = false
                    document.onmousemove = null
                    document.onmouseup = null
                }
            }
            drag.status = true
            drag.lastX = event.clientX
            drag.lastY = event.clientY
        }
    }
}

使用方式

openImagePreview("./1719194464803.jpg");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值