为什么在SVG中图像无法正确缩放?

时间:2019-01-22 14:45:59

标签: javascript svg svg-edit

我正在从用户那里获取输入(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>

我也尝试过背景尺寸,但是效果不佳。

我该如何实现?

3 个答案:

答案 0 :(得分:1)

之所以会这样,是因为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"

答案 1 :(得分:0)

您可以尝试使用%代替px吗?

还请通过检查开发人员工具中的图像来检查高度和宽度是否正在更新。

此外,尝试从开发人员工具更新属性值,并观察哪个工作正常。

答案 2 :(得分:0)

例如,您必须将image设置为preserveAspectRatio

preserveAspectRatio="xMidYMid slice"
相关问题