Image SVG图像的自动宽度和高度

Image SVG图像的自动宽度和高度,image,svg,d3.js,Image,Svg,D3.js,我不熟悉SVG,如果这是一个很难回答的问题,我很抱歉。我正试图弄清楚如何让一幅图像以参考图像的全宽和全高显示。我正在使用D3.js构建一个图形,我希望在角落中显示一个徽标。问题是图像href将使用javascript进行设置,因此所引用的图像永远不是固定的宽度或高度。我想要的是图像显示在它的全宽和全高,而不是放大或缩小。我所希望的是能够根据图像内容自动设置图像的宽度和高度,例如将width和height属性设置为auto。但是,这只会导致图像无法显示 d3.select("body") .a

我不熟悉SVG,如果这是一个很难回答的问题,我很抱歉。我正试图弄清楚如何让一幅图像以参考图像的全宽和全高显示。我正在使用
D3.js
构建一个图形,我希望在角落中显示一个徽标。问题是图像
href
将使用javascript进行设置,因此所引用的图像永远不是固定的宽度或高度。我想要的是图像显示在它的全宽和全高,而不是放大或缩小。我所希望的是能够根据图像内容自动设置图像的宽度和高度,例如将
width
height
属性设置为
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');
d3.选择(“主体”)
.append(“svg”)
.attr('id','mySVG'))
艾特先生({
“宽度”:“100%”,
“高度”:“100%”
})
.attr(“视图框”,“0 0”+宽度+“”+高度)
.attr(“保留Aspectratio”、“无”);
d3.选择(“#mySVG”)
.append('图像')
.attr('image-rendering','optimizeQuality')

.attr('height','auto')我认为'auto'不是svg图像元素的'length'attr的有效值。看看规格。您可能希望使用“100%”

您可以加载图像,然后在加载时检查宽度和高度

JSFiddle:


自从有人问起这个问题已经有几年了,但我目前正试图确定一些关于使用
auto
作为宽度或高度值的事情,我想我会分享我的发现。根据on scaling SVG和she提供的,如果您将
auto
作为
宽度或
高度
值以及
视图框
的值放入,您应该能够按比例看到内容缩放。不幸的是,她还指出,当时这只适用于“Blink/Firefox”浏览器,所以现在Chrome也有可能支持这一点。我看到Chrome中的行为似乎支持这种可能性,但我也得到了一个错误,所以YMMV。

有什么理由不只是使用img标签吗?嗨,Wex。你是说
html
img
标签?如果可能的话,我更愿意将解决方案保存在
SVG
中。要将图像嵌入正在构建的图形的
SVG
。可能的重复
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)

}
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";
    });