Accepted answer

Images with height or width of zero or unset are not getting rendered:

<!DOCTYPE html>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <script src=""></script>


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

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

        .attr('xlink:href', '')
        .attr('x', 20)
        .attr('y', 20)
        .attr('height', 20)
        .attr('width', 20)




So set height and width and it will work properly.


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