【问题标题】:Scale overriding SVG width and height attributes缩放覆盖 SVG 宽度和高度属性
【发布时间】:2017-08-07 14:17:01
【问题描述】:

我有一个定义了宽度和高度的 SVG 元素,例如 <svg width="100px" height="100px"></svg>,其中填充了各种元素。

我想要一种“缩放”功能,将 SVG 的特定区域放大以填充整个 SVG 元素。

我计划使用 scale 和 translate 属性来执行此操作,即将scale(x) 应用于 SVG 元素,然后计算我需要翻译的内容以使所需区域保持可见。

我预计这将使 SVG 保持在 100x100 像素,并简单地隐藏该区域之外的任何元素。但是,这不会发生。整个 SVG 元素反而变得更大了,即使维度被明确定义为属性。

显然我误解了缩放和 SVG 尺寸的工作方式,有谁知道我如何才能在这里实现我想要做的事情?

【问题讨论】:

    标签: javascript html css svg scale


    【解决方案1】:

    您可以使用 div 元素扭曲 svg 并使用溢出:隐藏。

    <div style="width: 300px; height: 300px; overflow: hidden">
      <svg width="100" height="100" style="transform: scale(4);">
         <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
      </svg> 
    </div>
    

    【讨论】:

      【解决方案2】:

      你的意思是这样的吗?

      function setViewBox(vbx){
        svg.setAttribute("viewBox",vbx)
      }
      <svg viewBox="0 0 100 100" width="200px" height="200px" id="svg">
        <rect x="0" y="0" width="100" height="100" stroke="black" fill="white" onclick="setViewBox('0 0 100 100')"/>
        <circle cx="25" cy="25" r="25" fill="red" onclick="setViewBox('0 0 50 50')"/>
        <rect x="60" y="10" width="30" height="30" fill="green" onclick="setViewBox('50 0 50 50')"/>
        <rect x="10" y="60" width="30" height="30" fill="blue" transform="rotate(45,25,75)" onclick="setViewBox('0 50 50 50')"/>
        <path d="M50 100L75 50L100 100z" fill="yellow" onclick="setViewBox('50 50 50 50')"/>
      </svg>

      还是更多?

      var last=null
      function setTransform(evt,trs){
        reset()
        svg.appendChild(evt.target)
        evt.target.setAttribute("transform","scale(2 2) translate("+trs+")")
        last=evt.target
      }
      function reset(){
        if(last) last.removeAttribute("transform")
      }
      <svg viewBox="0 0 100 100" width="200px" height="200px" id="svg">
        <rect x="0" y="0" width="100" height="100" stroke="black" fill="white"  onclick="reset()"/>
        <circle cx="25" cy="25" r="25" fill="red" onclick="setTransform(event,'0 0')"/>
        <rect x="60" y="10" width="30" height="30" fill="green" onclick="setTransform(event,'-50 0')"/>
        <rect x="10" y="60" width="30" height="30" fill="blue" transform="rotate(45,25,75)" onclick="setTransform(event,'0 -50')"/>
        <path d="M50 100L75 50L100 100z" fill="yellow" onclick="setTransform(event,'-50 -50')"/>
      </svg>

      【讨论】:

        猜你喜欢
        • 2013-11-26
        • 2013-12-24
        • 1970-01-01
        • 1970-01-01
        • 2017-11-25
        • 2017-11-03
        • 1970-01-01
        • 2013-05-25
        • 1970-01-01
        相关资源
        最近更新 更多