svg image tag size

2020-03-26 07:12发布

<!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>

within the image tag, is it a must to state the width="87" height="66"? i want to let the image to display its original size(e.g the original size is width="180" height="120"), is it to possible to do that ?

in this case, if i remove width="87" height="66", the whole svg will display nothing.

<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>

thanks

标签: html svg
1条回答
对你真心纯属浪费
2楼-- · 2020-03-26 07:45

You need to understand that the width and height are the bounds of the image viewport, not the "size" of the image. Put another way those values are the MAXIMUM area that image should occupy. If a raster (bitmap) image turns out to be smaller or larger than that area then the scaling and positioning are controlled by the preserveAspectRatio attribute. If you don't set width and height they default to 0 which is why you aren't seeing anything. The spec says:

An ‘image’ element establishes a new viewport for the referenced file as described in Establishing a new viewport. The bounds for the new viewport are defined by attributes ‘x’, ‘y’, ‘width’ and ‘height’. The placement and scaling of the referenced image are controlled by the ‘preserveAspectRatio’ attribute on the ‘image’ element.

So the solution you're looking for is to set the width/height to the maximum area you expect an image to fill and then set preserveAspectRatio to the appropriate value to set the scale and position the way you want (the spec provides an example SVG showing some of the possible behaviours for preserveAspectRatio).

查看更多
登录 后发表回答