SVG图像的自动宽度和高度

时间:2013-04-13 15:50:15

标签: image svg d3.js

我是SVG的新手,很抱歉,如果这是一个noob问题。我试图弄清楚如何使用引用图像的全宽和高度来显示图像。我正在使用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图像widthheight

3 个答案:

答案 0 :(得分:22)

我认为'auto'不是svg图像元素的'length'attr的有效值。看看规范here。您可能想要使用'100%'

可以加载图像然后检查宽度和高度onload。

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)

}

答案 1 :(得分: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";
    });

答案 2 :(得分:2)

自从问过这几年之后,我现在正试图确定一些关于使用auto作为宽度或高度值的事情,我想我会分享一下我找到了。根据{{​​3}}缩放SVG及其提供的Amelia Bellamy-Royds' 2015 article ,如果您将auto作为width的{​​{1}}或height值。 }},以及<svg>的值,您应该能够按比例查看内容缩放。不幸的是,她还指出,当时这只适用于&#34; Blink / Firefox&#34;浏览器。 codepen example,所以现在Chrome也可以支持这一点。我看到Chrome中的行为似乎支持这种可能性,但我也得到了错误,所以YMMV。

相关问题