SVG图像的自适应宽高

24

我对SVG不太熟悉,如果这是一个初学者问题,那就不好意思了。 我正在尝试弄清楚如何使图像显示为引用图像的完整宽度和高度。 我正在使用D3.js构建一个图形,我想让一个标志出现在角落里。 问题是,图像href将使用JavaScript设置,因此被引用的图像永远不是固定的宽度或高度。 我想要的是图像以其完整的宽度和高度显示,而不是缩放。 我希望能够自动设置图像的宽度和高度,基于其内容,例如将widthheight属性设置为auto。但是这只会导致图像不显示。

d3.select("body")
  .append("svg")
  .attr('id','mySVG')
  .attr({
      "width": "100%",
      "height": "100%"
  })
  .attr("viewBox", "0 0 " + width + " " + height )
  .attr("preserveAspectRatio", "none");

d3.select('#mySVG')
  .append('image')
  .attr('image-rendering','optimizeQuality')
  .attr('height','auto')     <--- This does not work
  .attr('width','auto')      <--- This does not work
  .attr('xlink:href', logoUrl)
  .attr('x','0')
  .attr('y','0');

我该如何指定SVG图像的宽度高度,以便根据引用图像的大小动态确定?


你为什么不直接使用img标签呢? - Wex
1
嗨Wex。你是指一个htmlimg标签吗?如果可能的话,我更喜欢在SVG中保留解决方案。希望将图像嵌入到正在构建的图表的SVG中。 - BruceHill
可能是Doesn't SVG support auto width and height for images?的重复问题。 - Erik Dahlström
3个回答

29

我认为在svg图像元素的'length'属性中,'auto'不是一个有效的取值。请查看这里的规范。你可能想使用'100%'。

你可以在加载图片后检查其宽度和高度。

JSFiddle: http://jsfiddle.net/WQBPC/4/

var logoUrl = 'http://placehold.it/100x50&text=Logo';

//SVG Setup stuff
var svg =  d3.select("body").append("svg")
  .attr('id','mySVG')
  .attr({
      "width": '100%',
      "height": '100%'
  })

var svg_img=  svg.append('image')
  .attr('image-rendering','optimizeQuality')
  .attr('x','0')
  .attr('y','0');

//Load image and get size.
var img = new Image();
img.src = logoUrl;
img.onload = function() {
 var width = this.width;
 var height = this.height;

 svg_img .attr('height', height)
  .attr('width',width)
  .attr('xlink:href', logoUrl)

}

3
d3.select("svg")
  .append("image")
    .attr("id", "myImage")
    .attr("xlink:href", "myImage.png")
    .on("load", function(d) { 
        var myImage = new Image();
        myImage.onload = function() {
            d3.select("#myImage")
                .attr("width", this.width)
                .attr("height", this.height);
        }
        myImage.src = "myImage.png";
    });

3

虽然这个问题已经被问了几年,但我目前正在尝试确定关于使用auto作为宽度或高度值的一些事情,并且想分享一下我所发现的。根据Amelia Bellamy-Royds 2015年的文章关于缩放SVG和她提供的codepen示例,如果您将auto作为<svg>widthheight值之一,以及viewBox的值,您应该能够看到内容按比例缩放。不幸的是,她还指出,当时这仅适用于“Blink / Firefox”浏览器。 Blink是WebKit的一部分分支, 所以现在Chrome也可能会支持这一点。我在Chrome中看到了支持这种可能性的行为,但我也遇到了错误,因此可能因人而异。


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