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

如何按200%比例放大SVG并保持其宽高比

解决SVG放大200%及跨页面生成放大路径的问题

问题根源

你修改width/height没生效,核心原因是原SVG的viewBox设置与路径坐标不匹配:
原viewBox="20 40 2 555"定义的可视区域仅覆盖x:2022、y:40595的范围,但你的路径坐标(如M345.1,302.4)完全在这个区域外,导致修改尺寸只是缩放了空的可视区域,看不到路径变化。


分步解决方案

1. 先修正原SVG的可视范围

首先调整viewBox,让它完全包含你的路径。通过分析路径坐标,其范围为:

  • x: 345.1 ~ 365.4(345.1 + 20.3)
  • y: 276 ~ 308.7(276 + 32.7)

修正后的基础SVG:

<svg width="204" height="327" viewBox="345 276 20.4 32.7" style="outline: 1px solid #666;">
  <path data-map-id="1" style="fill: #d9534f" class="st3" d="M345.1,302.4V276c0-3.5,2.8-6.3,6.3-6.3h20.3v32.7H345.1z" onclick="selectPath(this)"/>
</svg>

这里width/height是viewBox尺寸的10倍(方便查看),你可以根据需要调整比例。

2. 实现200%放大的两种方式

方式一:CSS缩放(快速预览用)

直接用transform: scale(2)缩放整个SVG,无需修改路径坐标:

<svg width="204" height="327" viewBox="345 276 20.4 32.7" style="outline: 1px solid #666; transform: scale(2); transform-origin: top left;">
  <path data-map-id="1" style="fill: #d9534f" class="st3" d="M345.1,302.4V276c0-3.5,2.8-6.3,6.3-6.3h20.3v32.7H345.1z"/>
</svg>

transform-origin: top left确保缩放从左上角开始,避免偏移。

方式二:修改路径坐标(跨页面生成用)

提取路径的所有坐标并乘以2,生成真正放大的路径数据,适合跨页面传递:

function selectPath(path) {
  // 提取路径d属性,将所有数字坐标放大2倍
  const originalD = path.getAttribute('d');
  const scaledD = originalD.replace(/(\d+\.?\d*)/g, match => parseFloat(match) * 2);
  
  // 用localStorage存储放大后的路径数据(也可用URL参数传递)
  localStorage.setItem('scaledPath', scaledD);
  // 跳转到目标页面
  window.location.href = 'target-page.html';
}

3. 目标页面生成放大的SVG

在target-page.html中读取存储的路径数据,生成放大后的SVG:

<svg id="scaledSvg" style="outline: 1px solid #666;"></svg>
<script>
  const scaledD = localStorage.getItem('scaledPath');
  if (scaledD) {
    const svg = document.getElementById('scaledSvg');
    // 设置匹配放大后路径的viewBox和尺寸
    svg.setAttribute('viewBox', '690 552 40.8 65.4');
    svg.setAttribute('width', '408');
    svg.setAttribute('height', '654');
    
    // 创建放大后的路径元素
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('d', scaledD);
    path.setAttribute('style', 'fill: #d9534f');
    path.setAttribute('class', 'st3');
    svg.appendChild(path);
    
    // 清理缓存
    localStorage.removeItem('scaledPath');
  }
</script>

内容的提问来源于stack exchange,提问作者Paul Holness

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:02:55