Javascript Reference - HTML DOM Image naturalWidth Property








The read-only naturalWidth property returns the original width of an image.

Browser Support

naturalWidth Yes Yes Yes Yes Yes

Syntax

var v = imageObject.naturalWidth

Return Value

A Number type value representing the original width of an image in pixels.





Example

The difference between the naturalWidth property and the width property.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" style="width:100px;height:100px;">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function myFunction() {<!--  w  w w  .j a v a2 s .  c om-->
    var x = document.getElementById("myImg").naturalWidth;
    document.getElementById("demo").innerHTML = "The original width: " + x + " pixels";
    
    var y = document.getElementById("myImg").width;
    document.getElementById("demo2").innerHTML = "The 'styled' width: " + y + " pixels";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the original width of an image.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" style="width:100px;height:100px;">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!-- ww w  . j  av a  2  s  .  c om-->
    var x = document.getElementById("myImg").naturalWidth;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: