利用原生JS實(shí)現(xiàn)圖片的拖拽與縮放

復(fù)制代碼就可以使用了

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
      #box {
          width: 100px;
          height: 100px;
          background-color: aquamarine;
          position: absolute;
      }
      #father {
        width: 600px;
        height: 500px;
        background-color: rgb(226, 117, 184);
        position: relative;
      }
      img {
        width: 100%;
        height: 100%;
        cursor: move;
      }
      #scale { 
        width: 10px; 
        height: 10px; 
        overflow: hidden; 
        cursor: se-resize; 
        position: absolute; 
        right: 0; 
        bottom: 0; 
        background-color: rgb(122, 191, 238); 
      }
  </style>

</head>
<body>
    <div id="father">
      <div id="box">
        <img src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"/>
        <div id="scale"></div>
      </div>
    </div>
    <script type="text/javascript">
    // box是裝圖片的容器,fa是圖片移動(dòng)縮放的范圍,scale是控制縮放的小圖標(biāo)
        var box = document.getElementById("box");
        var fa = document.getElementById('father');
        var scale = document.getElementById("scale");
        // 圖片移動(dòng)效果
        box.onmousedown=function(ev) {
            var oEvent = ev; 
            // 瀏覽器有一些圖片的默認(rèn)事件,這里要阻止
            oEvent.preventDefault();
            var disX = oEvent.clientX - box.offsetLeft;
            var disY = oEvent.clientY - box.offsetTop;
            fa.onmousemove=function (ev) {
                oEvent = ev;
                oEvent.preventDefault();
                var x = oEvent.clientX -disX;
                var y = oEvent.clientY -disY;

                // 圖形移動(dòng)的邊界判斷
                x = x <= 0 ? 0 : x;
                x = x >= fa.offsetWidth-box.offsetWidth ? fa.offsetWidth-box.offsetWidth : x;
                y = y <= 0 ? 0 : y;
                y = y >= fa.offsetHeight-box.offsetHeight ? fa.offsetHeight-box.offsetHeight : y;
                box.style.left = x + 'px';
                box.style.top = y + 'px';
            }
            // 圖形移出父盒子取消移動(dòng)事件,防止移動(dòng)過快觸發(fā)鼠標(biāo)移出事件,導(dǎo)致鼠標(biāo)彈起事件失效
            fa.onmouseleave = function () {
              fa.onmousemove=null;
              fa.onmouseup=null;
            }
            // 鼠標(biāo)彈起后停止移動(dòng)
            fa.onmouseup=function() {
               fa.onmousemove=null;
               fa.onmouseup=null;
            } 
        }
        // 圖片縮放效果
        scale.onmousedown = function (e) {
          // 阻止冒泡,避免縮放時(shí)觸發(fā)移動(dòng)事件
          e.stopPropagation();
          e.preventDefault();
          var pos = {
            'w': box.offsetWidth,
            'h': box.offsetHeight,
            'x': e.clientX,
            'y': e.clientY
          };
          fa.onmousemove = function (ev) {
            ev.preventDefault();
            // 設(shè)置圖片的最小縮放為30*30
            var w = Math.max(30, ev.clientX - pos.x + pos.w)
            var h = Math.max(30,ev.clientY - pos.y + pos.h)
            // console.log(w,h)

            // 設(shè)置圖片的最大寬高
            w = w >= fa.offsetWidth-box.offsetLeft ? fa.offsetWidth-box.offsetLeft : w
            h = h >= fa.offsetHeight-box.offsetTop ? fa.offsetHeight-box.offsetTop : h
            box.style.width = w + 'px';
            box.style.height = h + 'px';
            // console.log(box.offsetWidth,box.offsetHeight)
          }
          fa.onmouseleave = function () {
            fa.onmousemove=null;
            fa.onmouseup=null;
          }
          fa.onmouseup=function() {
            fa.onmousemove=null;
            fa.onmouseup=null;
          } 
        }
        
    </script>
</body>
</html>

縮放有很多種的方法可以通過控制transform樣式修改

1.通過鼠標(biāo)滾動(dòng)控制圖片的縮放

// 鼠標(biāo)滾動(dòng)事件
img.onwheel = function (event) {
     // console.log(event.wheelDelta);
     event.stopPropagation();
     event.preventDefault();
     if (event.wheelDelta > 0) {
         indexs = (indexs * 1 + 0.1).toFixed(1);
         img.style.transform = `scale(${indexs})`;
     } else {
         if (indexs == 0.5) {
             indexs = 0.5;
             img.style.transform = `scale(${indexs})`
         } else {
             indexs = (indexs - 0.1).toFixed(1)
             img.style.transform = `scale(${indexs})`
         }
     }
 }

2.通過按鈕控制圖片的縮放

var btnmagnify = document.createElement('button');
btnmagnify.classList.add('btnmagnify', 'el-icon-zoom-in')
var indexs = 1;
var indexdeg = 0;
btnmagnify.onclick = function (e) {
    e.stopPropagation()
    indexs = (indexs*1 + 0.1).toFixed(1)
    img.style.transform = `scale(${indexs}) rotate(${indexdeg}deg)`;
}

var btnreduce = document.createElement('button');
btnreduce.classList.add('btnreduce', 'el-icon-zoom-out')
btnreduce.onclick = function (e) {
    e.stopPropagation();
    if (indexs == 0.5) {
        indexs = 0.5;
        img.style.transform = `scale(${indexs}) rotate(${indexdeg}deg)`;
    } else {
        indexs = (indexs - 0.1).toFixed(1)
        img.style.transform = `scale(${indexs}) rotate(${indexdeg}deg)`
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容