0

我正在尝试将任意图像放置为具有固定大小的 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>
4

1 回答 1

1

没有办法(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 寻求帮助。

于 2013-11-06T20:54:26.280 回答