[英]Why image doesn't scale properly in SVG?
我從用戶那里獲取輸入 (x,y,高度和寬度)以通過javascript在SVG中創建動態img 。
它可以正常工作,但“高度”和“寬度”不會根據該值縮放(它充當圖像的填充)。 高度和寬度不會增加或減少。
這是我的代碼(僅與問題有關):
Grp = document.createElementNS('http://www.w3.org/2000/svg', 'g')
Grp.setAttributeNS(null, "id", "newGrp");
svg.appendChild(Grp);
Img = document.createElementNS('http://www.w3.org/2000/svg', 'image');
Img.setAttributeNS(null, "id", "newImg");
Img.setAttributeNS(null, "x", x);
Img.setAttributeNS(null, "y", y);
Img.setAttributeNS(null, "height", height);
Img.setAttributeNS(null, "width", width);
Img.setAttributeNS(null, "style", "height:" + height + "px;width:" + width+"px;");
//Img .setAttributeNS(null, "style", "background-size:" + height + " " + width + ";");
Img .setAttributeNS('http://www.w3.org/1999/xlink', "href", PathofImage);
Grp.appendChild(Img);
這是SVG的外觀
<svg xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"
width="500" height="100" overflow="visible" x="500"
y="500" viewBox="0 0 700 700">
<g id="newGrp">
<image id="newImg" x="108.3" y="375.3" height="48.5" width="144.3"
style="background-size:38.5 134.3;"
xlink:href="pathofImage"></image>
<g>
<svg>
我也嘗試過background-size,但是效果不佳。
我該如何實現?
這是發生由於寬度和您的SVG元素的高度不匹配的viewbox
。 在您的情況下, viewBox="0 0 700 700"
這意味着您的svg畫布從(0,0)開始,具有700個用戶單位的寬度和700個用戶單位的高度。 SVG的大小為width="500" height="100"
。 要匹配wiewBox,您需要width="500" height="500"
或width="100" height="100"
請查看與視圖框大小相同的矩形會發生什么情況:
svg{border:1px solid;}
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" width="500" height="100" overflow="visible" x="500" y="500" viewBox="0 0 700 700"> <rect width="700" height="700" /> </svg>
也許這是您需要的:
svg{border:1px solid;}
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" overflow="visible" viewBox="0 0 700 700"> <g id="newGrp"> <rect x="108.3" y="375.3" height="48.5" width="144.3" fill="none" stroke="black" /> <image id="newImg" x="108.3" y="375.3" height="48.5" width="144.3" style="background-size:38.5 134.3;" xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/%20BrianArnesen.svg"></image> <g> <svg>
或者,您可能希望將viewBox更改為諸如viewBox="0 0 500 100"
您可以嘗試使用%而不是px嗎?
另外,請通過檢查開發人員工具中的圖像來檢查高度和寬度是否正在更新。
另外,嘗試從開發人員工具更新屬性值,並觀察哪個工作正常。
例如,您必須為image
設置preserveAspectRatio
preserveAspectRatio="xMidYMid slice"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.