21

私はに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');

widthSVG 画像を指定するにはどうすれheightばよいですか?参照される画像サイズに基づいて動的に決定する必要がありますか?

4

3 に答える 3

26

「auto」は、svg 画像要素の「長さ」属性の有効な値ではないと思います。こちらの仕様をご覧ください。「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)

}
于 2013-04-14T15:39:48.430 に答える
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";
    });
于 2015-06-07T04:53:54.280 に答える