2017-08-07 108 views
0

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

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

我打算通过scaletranslate属性来完成此操作,即将scale(x)应用于SVG元素,然后计算我需要翻译的内容以便让所需区域保持可见。

我预计这会使SVG保持在100x100px,并且简单地隐藏该区域以外的任何元素。但是,这不会发生;整个SVG元素只是变得更大,即使这些维度明确定义为属性。

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

回答

0

你可以使用div元素扭曲svg并使用overflow:hidden。

<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> 
0

你的意思是这样的吗?

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>