如何获取SVG <image>元素的自然尺寸?

9
在HTML中,我们有一个称为<img>的元素,它与Image对象有些相似。两者都有两个属性叫做naturalWidthnaturalHeight。当您想要将图像的尺寸设置为其自然尺寸时,可以在load回调中轻松完成此操作。
var img = new Image
img.addEventListener('load' function(e) {
    // do whatever with naturalWidt/Height
})

但是,当你想要设置svg <image>元素的尺寸时,你不能依赖它,因为该元素没有natural属性:

var img = document.createElementNS(namespace, 'image')
img.addEventListener('load' function(e) {
    img.setAttributeNS(namespace, 'width', img.naturalWidth) // dont work
})

所以我的问题是:如何在不加载图像的情况下设置svg <image>元素的尺寸?是否有计划在规范中支持这样的自然属性?

我发现自己也在想同样的问题。你有找到答案吗? - MichaelPlante
我所做的基本上是加载一个图像对象,当它加载完成后,我将我的SVG图像更改为所需的宽度和高度。也许我应该向邮件列表提问。 - Fuzzyma
1个回答

1

Svg <image> 元素缺少 widthheight 属性,默认使用自然像素尺寸。

然而,通过调整它的 viewBox 或实际布局 withheight父级svg元素不会自动增长。

getBBox()

使用svg getBBox() 方法检索任何"可渲染元素"的边界框。

类似于HTML的 <img> 元素,我们需要等待图像src加载完成。

getBBox() 需要一个元素添加到DOM中 - 否则它返回一个0x0的边界框。

示例:附加svg <image>,加载src并调整svg大小

let svg = document.getElementById("svg");

function loadImg(href) {
  // create namespaced svg element
  let ns = "http://www.w3.org/2000/svg";
  let image = document.createElementNS(ns, "image");
  // set href
  image.setAttribute("href", href);
  svg.appendChild(image);

  image.addEventListener("load", (e) => {
    // get bounding box
    let bb = e.currentTarget.getBBox();
    let [width, height] = [bb.width, bb.height];
    image.setAttribute("width", width);
    image.setAttribute("height", height);
    //adjust viewBox
    svg.setAttribute("viewBox", [0, 0, width, height].join(" "));
    // optional - if you resize your svg via css
    svg.setAttribute("width", width);
    svg.setAttribute("height", height);
  });
}
svg{
  overflow:visible;
  border:1px solid red;
  background:#ccc;
}
<p><button type="button" onclick="loadImg('https://placehold.co/600x400')">load image</button></p>
<svg id="svg" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 100 100">
</svg> adjacent text. 

由于浏览器通常会缓存图像请求,因此您也可以使用上述的new image()方法来获取naturalWidth并将其应用于svg <image>如此描述


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