If you have prior knowledge of your image's dimensions on the server side, the most convenient approach is to set it when rendering the HTML. You can specify the width and height attributes of the <img>
tag to determine its size, along with adjusting its margin-left and margin-top properties to center it within a container. This method enhances user experience by preventing screen flickering when resizing the image via JavaScript after loading. It is considered the optimal way to achieve this goal.
Edit: As mentioned in the comments, employing a server-side solution may require implementing a JavaScript function on $(window).resize() to ensure the image remains centered and properly sized if the user adjusts the window dimensions.
--
However, given that your inquiry relates to JavaScript, the process involves working in two stages: first, decrease the image's height and width to fit within the window without distorting its aspect ratio, followed by applying margins to horizontally and vertically center it.
An example demonstrating the desired outcome is provided below. Please note that while this code is not optimized and should not be directly used, it is presented in an explanatory manner for ease of comprehension.
The HTML:
<body>
<div id="main" style="margin: 0; padding: 0">
<img id="yourpic" src="http://domain.com/image.png" />
</div>
</body>
The JS:
// Utilize the onLoad event to obtain image dimensions
$('#yourpic').load(function() {
// Cache relevant elements
var $window = $(window);
var $this = $(this);
var tmp;
// Adjust the width of the image if it exceeds the window width, maintaining its aspect ratio
if ($window.width() < this.width) {
tmp = [this.width, this.height];
$this.width($window.width());
$this.height(tmp[1] / (tmp[0] / this.width));
}
// Follow the same procedure for height
if ($window.height() < this.height) {
tmp = [this.height, this.width];
$this.height($window.height());
$this.width(tmp[1] / (tmp[0] / this.height));
}
// Horizontal centering
if ($window.width() > this.width) {
$this.css('margin-left', ($window.width() - this.width) / 2);
}
// Vertical centering
if ($window.height() > this.height) {
$this.css('margin-top', ($window.height() - this.height) / 2);
}
});
View the example implementation here: http://jsfiddle.net/RPCjE/2/ (Note: The img.onload event in Chrome is known to be buggy, so users of this browser may need to refresh without caching).