HTML 5 平移缩放的demo(类似地图效果)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>一个平移缩放的demo</title>
  <style>
    .container {
      border: 1px solid #ddd;
      width: 1600px;
      height: 900px;
      box-sizing: content-box;
      overflow: hidden;
    }
    .scene {
      position: relative;
      background: #ddd;
      width: 1600px;
      height: 900px;
      cursor: grab;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="scene" class="scene">
      这是一个平移缩放的demo,这是一个平移缩放的demo。<br>
      <div id="el">点我试试</div>

    </div>
  </div>
  <script src='https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js'></script>
  <script>
    // just grab a DOM element
    var scene = document.querySelector('#scene')

    // And pass it to panzoom
    var instance = panzoom(scene, {
      maxZoom: 10,
      minZoom: 1,
      transformOrigin: { x: 0, y: 0 },
      initialX: 0,
      initialY: 0,
      initialZoom: 1.5
    })

    function reset() {
      const width = 1600
      const height = 900

      let obj = instance.getTransform()
      // 左上角
      if (obj.x > 0) {
        instance.moveTo(0, obj.y);
      }
      if (obj.y > 0) {
        instance.moveTo(obj.x, 0);
      }
      // 右下角
      if (obj.x < - width * (obj.scale - 1)) {
        instance.moveTo(- width * (obj.scale - 1), obj.y);
      }
      if (obj.y < - height * (obj.scale - 1)) {
        instance.moveTo(obj.x, - height * (obj.scale - 1));
      }

      // console.log(obj)

    }
    // 平移或缩放
    instance.on('transform', function (e) {
      reset()
    })

    // 点击事件
    var el = document.getElementById('el')
    el.addEventListener('click', function (e) {
      alert('点击事件')
    })
  </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容