【问题标题】:Auto width and height for SVG imageSVG图像的自动宽度和高度
【发布时间】:2013-04-06 01:29:36
【问题描述】:

我是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 图像 widthheight 必须根据引用的图像大小动态确定?

【问题讨论】:

  • 你有什么理由不只使用 img 标签吗?
  • 嗨,Wex。你的意思是 html img 标签?如果可能的话,我更愿意将解决方案保留在SVG 中。想要嵌入在 SVG 中的图像用于正在构建的图形。

标签: image svg d3.js


【解决方案1】:

我认为 'auto' 不是 svg 图像元素的 'length' attr 的有效值。查看规范here。您可能想使用“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)

}

【讨论】:

    【解决方案2】:
    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 article on scaling SVGs 和她提供的codepen example,如果你把auto 作为widthheight&lt;svg&gt; 的值,以及viewBox 的值,您应该能够看到按比例缩放的内容。不幸的是,她还指出,当时这只适用于“Blink/Firefox”浏览器。 Blink is a fork of part of WebKit,所以现在 Chrome 也有可能支持这个。我在 Chrome 中看到了似乎支持这种可能性的行为,但我也收到了一个错误,所以 YMMV。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-26
        • 2018-01-13
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多