[英]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.