我可以缩小 SVG 的背景图像,但不能放大吗?



我正在尝试放置任意图像作为具有固定大小的SVG的背景。期望的行为是将大于 SVG 固定大小的图像统一缩放以适合框内(即"满足"而不是"剪辑"),以及较小的图像以以其原始大小显示。(它也应该居中,但我已经弄清楚了这部分。

大图像缩小很容易,但我还没有想出如何让小图像放大。有什么想法吗?这是一个与这个问题类似的问题,但对于 SVG 而不是 CSS。另一个问题肯定是相关的,但是因为我事先不知道图像的像素大小,所以解决方案对我没有帮助。

以下是当前 SVG 结构的简化版本,以 Placekitten 作为背景图像:

<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" xlinkns="http://www.w3.org/1999/xlink" width="640" height="480" x="640" y="480" overflow="visible">
  <svg id="canvasBackground" width="640" height="480" x="0" y="0" overflow="none" style="pointer-events:none">
    <rect width="100%" height="100%" x="0" y="0" stroke="#000" fill="#FFF" style="pointer-events:none"/>
    <image id="background_image" width="100%" height="100%" preserveAspectRatio="xMidYMid" style="pointer-events:none" href="http://placekitten.com/500/400/"/>
  </svg>
</svg>
没有

办法(AFAIK)通过SVG DOM获得图像的自然大小。 因此,您需要先使用 HTML DOM 加载图像以确定大小。

var  htmlImg = document.createElement("img");
// Add an onload listener so we know when it is loaded
htmlImg.addEventListener('load', function() {
    // Get the image width and height (modern browsers only unfortunately)
    var  w = htmlImg.naturalWidth;
    var  h = htmlImg.naturalHeight;
    // Now we can add an <image> element to the <svg>
    // ...
});
// Set the img src attribute to trigger the load
htmlImg.src = url;

这是一个工作演示。

此代码使用 HTMLImageElement 的 naturalWidthnaturalHeight 属性。 这些是旧版浏览器不支持的(例如。IE7/8)。 如果您需要支持较旧的浏览器,则必须做更多的工作。 搜索 SO 以获取有关此方面的帮助。

相关内容

最新更新