Auto width and height for SVG image

前端 未结 3 453
南方客
南方客 2021-02-07 04:36

I am new to SVG, so sorry if this is a bit of a noob question. I am trying to figure out how to get an image to display with the full width and height of the refere

3条回答
  •  日久生厌
    2021-02-07 05:03

    I don't think 'auto' is a valid value for the 'length' attr of a svg image element. Take a look at the spec here. You might want to use '100%'

    You could load the image then inspect the width and height 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)
    
    }
    

提交回复
热议问题