2017-08-07 109 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>