Preventing SVG background image from scaling

巧了我就是萌 提交于 2019-12-07 20:45:16

问题


I'm using SVG elements with masks to "knock out" or "punch out" text so that the underlying image can be shown through. The only problem with my current set up is that when the browser window is resized, the image elements stretch and distort, rather than staying at a fixed aspect ratio/size.

I've been pouring over the svg spec and have read about preserveAspectRatio but nothing seems to work.

Here's the basic element I'm using:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" xmlns:xlink="http://www.w3.org/1999/xlink">
          <defs>
            <mask id="masktext1">
              <rect width="100%" height="100%" fill="#fff" />
              <text width="100%" class="svgtext">TEXT 1</text>
            </mask>
          </defs>
          <image xlink:href="https://s3.amazonaws.com/f.cl.ly/items/1w3F3d130t2q1i2n2b2Y/pattern.png" mask="url(#masktext1)" width="100%" height="100%" x="0" y="0" preserveAspectRatio="xMinYMin slice" />
        </svg>

Here's a JS Fiddle example. Note that the issue is visible when you resize the window horizontally.

http://jsfiddle.net/785yjwws/


回答1:


The solution was found by reading up on viewBox as suggested by chipChocolate.py. I found this great article by on sarasoueidan.com which helped immensely. The end solution involved setting the width and height of the image element to be the full size of the background image, setting the width and height of the parent svg element programmatically for the space, and then setting viewBox = "0 0 [programmatic width] [programmatic height]" which frames the content.



来源:https://stackoverflow.com/questions/28220103/preventing-svg-background-image-from-scaling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!