SVG图像标签大小

4
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <body>
       <svg 
        xmlns="http://www.w3.org/2000/svg" 
        xmlns:xlink="http://www.w3.org/1999/xlink" 
        id="test1" 
        height="1000px" 
        width="1000px">
            <image id="testimg1" xlink:href="http://localhost/at/src/html5test/map1.png" width="87" height="66" x="0" y="0"/>

        </svg>
        </p>        
    </body>
</html>

在图像标签中,必须声明 width="87" height="66" 吗?我想让图像以其原始大小显示(例如,原始大小为 width="180" height="120"),这是可能的吗?

在这种情况下,如果我删除 width="87" height="66",整个 SVG 将不显示任何内容。

<svg 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    id="test1" 
    height="1000px" 
    width="1000px">
        <image id="testimg1" xlink:href="http://localhost/at/src/html5test/1.svg" x="0" y="0"  />
        <image id="testimg2" xlink:href="http://localhost/at/src/html5test/2.svg" x="19" y="127" />
        <image id="testimg3" xlink:href="http://localhost/at/src/html5test/3.svg" x="130" y="110"  />            

    </svg>

谢谢


2
你的问题表述不清楚。例如,图片的原始尺寸是多少,为什么你还没有使用它(你是否知道它的大小)?你是在寻找一个相对大小还是绝对大小?你想要实现什么效果?你是否查看了规格说明或尝试过不使用属性? - SpliFF
原始大小指该文件的图像尺寸。 - hkguile
还不清楚。为什么你没有把 width="87" 改成 width="120"?你是在说有一系列不同尺寸的图像,而这些尺寸你事先不知道吗? - SpliFF
@spliFF 是的,宽度和高度是未知的。 - hkguile
1个回答

7
你需要理解的是,宽度和高度是图像视口的边界,而不是图像的“大小”。换句话说,这些值是图像应占据的最大区域。如果光栅(位图)图像比该区域小或大,则缩放和定位由preserveAspectRatio属性控制。如果不设置宽度和高度,则默认为0,这就是为什么您没有看到任何内容的原因。规范说明如下:

“image”元素根据建立新视口文件所述建立新视口。新视口的边界由属性“x”、“y”、“width”和“height”定义。参考图像的定位和缩放由“image”元素上的“preserveAspectRatio”属性控制。

因此,你需要将宽度 / 高度设置为你期望图像填充的最大区域,然后将preserveAspectRatio设置为适当的值,以实现所需的缩放和位置(规范提供了一个示例SVG,展示了preserveAspectRatio的一些可能行为)。

preserveAspectRatio允许我们进行CSS等效的“background-size: contain”或“background-size: cover”的操作。https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio - Ideogram
一个 CodePen 用来演示 SpliFF 的答案(以及我的先前评论 :))http://codepen.io/ideogram/pen/apWLNG - Ideogram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接