![](/img/trans.png)
[英]Get svg graphics size when width/height attributes on <svg> are not set
[英]Scale overriding SVG width and height attributes
我有一個定義了寬度和高度的SVG元素,例如<svg width="100px" height="100px"></svg>
,其中填充了各種元素。
我想要一種“縮放”功能,其中SVG的特定區域被放大以填充整個SVG元素。
我計划使用scale
和translate
屬性來執行此操作,即通過將scale(x)
應用於SVG元素,然后計算需要進行哪些轉換才能使所需區域保持可見。
我期望這將使SVG保持在100x100px並僅隱藏該區域之外的任何元素。 但是,這不會發生。 即使將尺寸明確定義為屬性,整個SVG元素也會變大。
顯然,我誤解了縮放和SVG尺寸的工作方式,有誰知道我如何才能在這里實現自己的目標?
您可以使用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>
你的意思是這樣嗎?
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.