2013-04-13 163 views
14

我是SVG的新手,很抱歉,如果這是一個小問題。我想弄清楚如何讓圖像顯示引用圖像的全部寬度和高度。我正在使用D3.js來構建圖表,並且我希望角落中出現徽標。問題是,圖像href將使用JavaScript設置,因此被引用的圖像永遠不會是固定的寬度或高度。我想要的是圖像顯示在它的全寬和高度,而不是放大或縮小。我所希望的是能夠根據內容的內容自動設置圖像的寬度和高度,例如將widthheight屬性設置爲auto。然而,這只是導致圖像不顯示。SVG圖像的自動寬度和高度

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必須根據所引用的圖像大小來動態確定?

+0

你有沒有任何理由不使用img標籤? – Wex

+1

嗨Wex。你的意思是一個'html'' img'標籤?如果可能,我寧願將解決方案放在'SVG'中。希望爲正在構建的圖形嵌入'SVG'中的圖像。 – BruceHill

+0

[不SVG支持圖片的自動寬度和高度?]的可能重複(http://stackoverflow.com/questions/16080273/doesnt-svg-support-auto-width-and-height-for-images) –

回答

17

我不認爲'自動'是一個svg圖像元素'長度'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) 

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

這幾年,因爲這已經被問,但我目前正試圖確定對使用auto爲寬度或高度自我價值的一些事情,我以爲我會分享我發現的。據Amelia Bellamy-Royds' 2015 article上縮放SVGs她提供,如果你把auto作爲無論是widthheight價值的<svg>,具有爲viewBox值一起,你應該能夠看到的內容按比例縮放codepen example。不幸的是,她還指出,這在當時只適用於「Blink/Firefox」瀏覽器。 Blink is a fork of part of WebKit,所以現在Chrome可能也會支持這個功能。我看到Chrome中似乎支持這種可能性的行爲,但我也遇到了錯誤,所以YMMV。