结合antd的Modal弹窗做可放大缩小,拖拽的图片放大查看

import React, { useRef } from "react"
import { Modal } from "antd"
// import { observer } from "mobx-react" //引入mobx,为了下一行
// import $state from "state" //引入state主要方便管理多个弹出框时,改变不同弹窗的打开标识

const BigPicture = props => {

    const zoomImg = useRef(null)

    const handleImgZoom = e => {
        const { clientWidth, clientHeight, style, height, width } = zoomImg.current
        const value = height / width
        const num = 100
        const bool = height > width ? clientWidth < 2000 : clientHeight < 1500
        if (e.nativeEvent.deltaY <= 0 && bool) {
            style.maxWidth = "none"
            style.maxHeight = "none"
            style.width = width + num + "px"
            style.height = height + (num * value) + "px"
            style.left = style.left - 1 % +"px"
            style.top = style.top - 1 % +"px"
        } else if (e.nativeEvent.deltaY > 0) {
            if (width > 200 && height > 100) {
                style.width = width - num + "px"
                style.height = height - (num * value) + "px"
                style.left = style.left + 1 % + "px"
                style.top = style.top + 1 % + "px"
            }
        }
    }

    const prenentDefault = e => {
        e.prenentDefault()
    }

    const handleDrag = e => {
        const { style, offsetLeft, offsetTop } = zoomImg.current
        //在jsx格式中需要用e.persist(),此方法会从池中移除合成时间,否则clientX会是null
        const x = e.clientX - offsetLeft
        const y = e.clientY - offsetTop
        zoomImg.current.onmousemove = function (e) {
            style.left = e.clientX - x + "px"
            style.top = e.clientY - y + "px"
        }
        zoomImg.current.onmouseup = function () {
            zoomImg.current.onmousemove = null
        }
    }

    const closePicModal = e => {
        e.stopPropagation()
        $state[props.openPicFlag] = false
    }

    return (
        <Modal
            visible={$state[props.openPicFlag]}
            onCancel={closePicModal}
        >
            <div className='close-botton' onClick={closePicModal}>
                <i />
            </div>
            <img
                className='zoomImg'
                alt=''
                src={props.url}
                onWheel={handleImgZoom} //滚轮缩放
                onDragStart={prenentDefault}
                onMouseDown={e => { e.persist(); handleDrag(e) }}
                ref={zoomImg}
            />
        </Modal>
    )
}

export default BigPicture
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值