You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

仅在缩放后允许平移SVG(SVG大于视口)

预期结果
  • 未缩放SVG时无法执行平移操作,且SVG始终保持居中状态
  • SVG缩放后,允许将其平移至自身边界位置
问题描述
  • 使用「限制SVG平移范围在原始边界内」的方案时:未缩放状态下仍能平移,且缩放后无法平移到全部边界位置
  • 使用该方案评论区的调整方案时:缩放状态下平移功能正常,但未缩放时尝试平移,SVG会向右下方偏移,无法维持居中
当前实现代码

JavaScript 逻辑

let beforePan

beforePan = function (oldPan, newPan) {
  let stopHorizontal = false,
    stopVertical = false,
    gutterWidth = this.getSizes().width,
    gutterHeight = this.getSizes().height,
    // Computed variables
    sizes = this.getSizes(),
    leftLimit = -((sizes.viewBox.x + sizes.viewBox.width) * sizes.realZoom) + gutterWidth,
    rightLimit = sizes.width - gutterWidth - (sizes.viewBox.x * sizes.realZoom),
    topLimit = -((sizes.viewBox.y + sizes.viewBox.height) * sizes.realZoom) + gutterHeight,
    bottomLimit = sizes.height - gutterHeight - (sizes.viewBox.y * sizes.realZoom)

  customPan = {}
  customPan.x = Math.max(leftLimit, Math.min(rightLimit, newPan.x))
  customPan.y = Math.max(topLimit, Math.min(bottomLimit, newPan.y))
  
  return customPan
}

let panZoomController = svgPanZoom('#map', {
  fit: 1,
  center: true,
  minZoom: 1,
  zoomScaleSensitivity: 0.5,
  beforePan: beforePan
});

DOM结构与CSS样式

SVG(id为map)的嵌套层级:wrapper div → content div → #map SVG

对应的CSS样式:

.wrapper {
    margin: auto;
}

.content {
    background-color: silver;
    position: absolute;
    inset: 0 0 0 0;
}

#map {
    width: 100%;
    height: 100%;
    position: relative;
    display: block;
}

内容的提问来源于stack exchange,提问作者Joao Pereira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:50:30