svg平移缩放

作者: IT晴天 | 来源:发表于2018-06-06 16:09 被阅读48次

    svg平移缩放,我刚开始尝试的是自己处理外层容器的控制,结果发现能用,但是效果不太好,有拖尾现象,后来用个js库svg-pan-zoom即可。如果想支持手机端手势操作,需要先安装Hammer.js。

    这里简单示范下核心代码,首先在index.html添加相应的js文件:

      <script src="assets/libs/svg-map/js/lib/hammer.min.js"></script>
      <script src="assets/libs/svg-map/js/lib/svg-pan-zoom.min.js"></script>
    

    html中有这样一个svg标签:

    <svg id="svggroup"><svg>
    

    然后实现方法,查找该id元素初始化,最后在页面加载后调用即可:

    initZoomPan(){
        const eventsHandler = {
          haltEventListeners: ['touchstart', 'touchend', 'touchmove', 'touchleave', 'touchcancel']
        , init: function(options) {
            var instance = options.instance
              , initialScale = 1
              , pannedX = 0
              , pannedY = 0
            // Init Hammer
            // Listen only for pointer and touch events
            this.hammer = Hammer(options.svgElement, {
              inputClass: Hammer.SUPPORT_POINTER_EVENTS ? Hammer.PointerEventInput : Hammer.TouchInput
            })
            // Enable pinch
            this.hammer.get('pinch').set({enable: true})
            // Handle double tap
            this.hammer.on('doubletap', function(ev){
              instance.zoomIn()
            })
            // Handle pan
            this.hammer.on('panstart panmove', function(ev){
              // On pan start reset panned variables
              if (ev.type === 'panstart') {
                pannedX = 0
                pannedY = 0
              }
              // Pan only the difference
              instance.panBy({x: ev.deltaX - pannedX, y: ev.deltaY - pannedY})
              pannedX = ev.deltaX
              pannedY = ev.deltaY
            })
            // Handle pinch
            this.hammer.on('pinchstart pinchmove', function(ev){
              // On pinch start remember initial zoom
              if (ev.type === 'pinchstart') {
                initialScale = instance.getZoom()
                instance.zoom(initialScale * ev.scale)
              }
              instance.zoom(initialScale * ev.scale)
            })
            // Prevent moving the page on some devices when panning over SVG
            options.svgElement.addEventListener('touchmove', function(e){ e.preventDefault(); });
          }
        , destroy: function(){
            this.hammer.destroy()
          }
        }
        const element = document.querySelector('#svggroup');
        svgPanZoom(element, {
          zoomEnabled: true,
          controlIconsEnabled: true,
          dblClickZoomEnabled: false,
          fit: 1,
          center: 1, 
          customEventsHandler: eventsHandler
        });
      }
    

    注:至此其实已经完工了的,但貌似有个bug——配置选项有个参数controlIconsEnabled: false用于控制工具栏是否显示的,而我用时发现无效果,所以做了额外处理:

    let a = document.getElementById('svg-pan-zoom-controls');
    if(a){
       a.remove();
    }
    

    相关文章

      网友评论

        本文标题:svg平移缩放

        本文链接:https://www.haomeiwen.com/subject/bbybsftx.html