StephenAdams
StephenAdams

Reputation: 531

getting the height/width of an image that does not have height/width set

I'm working with a HTML page that has been created from a swf converter. The generated HTML uses SVG images to create the elements that match the layout of the swf.

I'm then trying to load in a image on top of these svg images, but unfortunately the svg images do not have the height and width set, so they look like this:

<div class="wlby_5">
    <!-- Start of symbol: element3 -->
    <img src="FlashTemplate_assets/svgblock_2.svg" class="wlby_4"></img>
    <!-- End of symbol: element3 -->
  </div>

When I append a image onto of this image, I can't get the original height and width to resize the image I'm loading so it resizes to match the original svg image. This is how I'm loading in the new image:

var imgWidth = $('div[class~="' + obj.name+ '"]').find('img').width()
var imgHeight = $('div[class~="' + obj.name+ '"]').find('img').height();


console.log("width of image", imgWidth);
console.log("height of image", imgHeight);
console.log( $('div[class~="' + obj.name+ '"]').find('img') );

$('div[class~="' + obj.name+ '"]').find('img').attr('src', obj.value);
$('div[class~="' + obj.name+ '"]').find('img').attr('width', imgWidth);
$('div[class~="' + obj.name+ '"]').find('img').attr('height', imgHeight);

So I'm trying to get the height and width of a image within the div layer, but these are not accessible, in the console they are both set as 0.

How can I access the height and width of the original svg image so I can apply it to the new image I'm loading?

Thanks

Stephen

Upvotes: 0

Views: 461

Answers (1)

Ben Carey
Ben Carey

Reputation: 16958

There are two methods to retrieve the height/width of an SVG image in these circumstances. Both methods work but I personally prefer the first.

Option 1

The getBBox() method of the SVGElement object can be used. This can retrieve the x and y offsets, as well as the width and height.

$('img').getBBox().width  
$('img').getBBox().height

Option 2

Alternatively, you can use the getBoundingClientRect() method like this:

$('img').getBoundingClientRect().width;

Upvotes: 1

Related Questions