我正在从用户那里获取输入(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>
我也尝试过背景大小,但效果不佳。
我怎样才能实现这个目标?
最佳答案
发生这种情况是因为 svg 元素的宽度和高度与 viewbox
不匹配。在您的情况下, viewBox="0 0 700 700"
这意味着您的 svg Canvas 从 (0,0) 开始,宽度为 700 个用户单位,高度为 700 个用户单位。 SVG 的大小为 width="500"height="100"
。要匹配 wiewBox,您需要 width="500"height="500"
或 width="100"height="100"
请看看与 View 框大小相同的矩形会发生什么:
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"
关于javascript - 为什么图像在 SVG 中无法正确缩放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54310746/