score:2

Accepted answer

Images with height or width of zero or unset are not getting rendered: https://developer.mozilla.org/de/docs/Web/SVG/Tutorial/SVG_Image_Tag

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script>

  </head>
  <body>

    <div id="viewImg"></div>
    <script>
      var w = 200;
      var h = 200;

      var svg = d3.select('#viewImg')
      .append('svg')
      .attr('width',w )
      .attr('height',h )
      .style('border', '1px solid #000');

      svg.append('svg:image')
        .attr('xlink:href', 'https://en.js.cx/clipart/ball.svg')
        .attr('x', 20)
        .attr('y', 20)
        .attr('height', 20)
        .attr('width', 20)
        .attr('id','plz');

      console.log(plz.getBBox());

    </script>

  </body>
</html>

So set height and width and it will work properly.

score:1

When you first run it, the browser hasn't loaded the image yet and reports image dimensions as 0. If you reload the page, the image is cached and Chrome (at least) reports on the correct image dimensions. If you know what your image dimensions are going to be, @Ruedi.Angehrn's answer will do the trick. If you need to use different images or don't know in advance what your image dimensions are going to be, you will need to use a different technique, for example by waiting for the page content to load fully before running getBBox().


Related Query