I'm trying to make a images scale in a square div of size 198px with overflow:hidden
The magic class refers to an img
$('.magic').on('load', function(){
var self = $(this);
var width = self.width();
var height = self.height();
if(width>height){
self.css('height', '198px');
self.css('width', 'auto');
}
else{
self.css('width', '198px');
self.css('height', 'auto');
}
});
Now the img is filling the div and not becoming bigger than it.
As in a landscape photo is not scaling perfectly but instead stretching.
See the fiddle: http://jsfiddle.net/powtac/VcLKL/19/
$(document).ready(function() {
$(".magic").each(function(){
var self = $(this);
var width = self.width();
var height = self.height();
if(width > height){
self.css('height', '198px');
var ratio = width / height;
self.css('width', 198 * ratio);
self.css('margin-left', ((198 - parseInt(self.css('width')))/2));
}
else{
self.css('width', '198px');
var ratio = height / width;
self.css('height', 198 * ratio);
self.css('margin-top', ((198 - parseInt(self.css('height')))/2));
}
});
});
Related
I am currently using the following javascript to resize an image to the size of it's parent, while maintaining aspect ratio and keeping the parent div square. So i have a square box with a rectangle stretched to either the max width or max height depending on orientation. This works great on first load however I cannot get the images and divs to resize on page orientation change or resize to work. Any ideas. I have tried using the window.resize and window.orientation listeners.
Original code was from:
Scale, crop, and center an image...
var aspHt = $('.aspectcorrect').outerWidth();
$('.aspectcorrect').css('height', aspHt + 'px').css('width', aspHt + 'px');
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {
var result = {
width : 0,
height : 0,
fScaleToTargetWidth : true
};
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
} else {
fScaleOnWidth = !fLetterBox;
}
if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
} else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth - result.width) / 2);
result.targettop = Math.floor((targetheight - result.height) / 2);
return result;
}
function RememberOriginalSize(img) {
if (!img.originalsize) {
img.originalsize = {
width : img.width,
height : img.height
};
}
}
function FixImage(fLetterBox, div, img) {
RememberOriginalSize(img);
var targetwidth = $(div).width();
var targetheight = $(div).height();
var srcwidth = img.originalsize.width;
var srcheight = img.originalsize.height;
var result = ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox);
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}
function FixImages(fLetterBox) {
$("div.aspectcorrect").each(function(index, div) {
var img = $(this).find("img").get(0);
FixImage(fLetterBox, this, img);
});
}
window.onload = function() {
FixImages(true);
};
Call .resize() after $(window).resize():
$(window).resize( function(){
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$("#landscape").css('display','none');
} else {
// Portrait
$("#landscape").css('display','block');
$("#landscape").click(function(){
$(this).hide();
});
}
}).resize();
I figured out what I was missing. The first bit of javascript is setting the style of height and width. When recalling the .outerHeight it was still using the inline style to calculate the width, and hence not resizing the div. I simply used .removeAttr('style') to remove that property first and then did the resize. Working now. I simply used $(window).on("resize", resizeDiv) and wrapped my resizing into a function named resizeDiv
function resizeDiv() {
var asp = $('.aspectcorrect');
asp.removeAttr("style");
var aspHt = asp.outerWidth();
asp.css('height', aspHt + 'px').css('width', aspHt + 'px');
FixImages(true);
}
I have an issue which is a little hard to explain. I have a div which has a 2:1 aspect ratio. And I want it to have a 100% width or height based on the browsers window size.
If the window height is greater than the divs height the the size should be based on 100% width.
And if window height is less than the divs height the size should be based on 100% height.
With my curren approach it is flashing when I size larger.
Look at this link http://acozmo.com/me/ for a demo.
HTML
<section id="container">
</section>
JQuery
function update() {
var $documentHeight = $(document).height();
var $windowHeight = $(window).height();
var $documentWidth = $(document).width();
var $windowWidth = $(window).width();
var $container = $('#container');
if ( $windowHeight >= $documentHeight ) {
$container.width($windowWidth);
$container.height($windowWidth / 2);
}
if ( $windowHeight < $documentHeight ) {
$container.width($windowHeight * 2);
$container.height($windowHeight);
}
}
$(document).ready(function() {
update()
});
$(window).resize(function() {
update();
})
To resize to fit inside the window while maintaining aspect ratio, set up your container with an initial size and then divide the area width by the container's width to get the scale. You then need a check to make sure that scale doesn't make the height too great. See code below and fiddle - I've added the case where the height is greater than the width too for completeness.
To stop the flashing, throttle your resize function using setTimeout. This will ensure that update is only called once every n milliseconds. You can play with the number until you find the right balance.
var container = $('#container'),
updateTimeout,
threshold = 100;
function update() {
var windowWidth = $(window).width(),
windowHeight = $(window).height(),
width = container.width(),
height = container.height(),
scale;
if ( windowWidth > windowHeight ) {
scale = windowWidth / width;
if ( height * scale > windowHeight ) {
scale = windowHeight / height;
}
}
else {
scale = windowHeight / height;
if ( width * scale > windowWidth ) {
scale = windowWidth / width;
}
}
container.width(Math.round(width * scale));
container.height(Math.round(height * scale));
}
$(document).ready(function() {
update();
});
$(window).resize(function() {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(update, threshold);
});
It's probably happening because the fact that you are using a second if, instead of an else . . . it hits the first if, shrinks the height, and then hits the second if and increases it.
Try changing this (the second if):
if ( $windowHeight < $documentHeight ) {
. . . to this:
else {
Here is the problem. I have
<div id="main"></div>
I want to check user resolution and change his height according user resolution, using javascript?
Javascript:
window.onload = function() {
var height = screen.height
document.getElementById(main).style.height = height;
};
I even try this:
window.onload = function() {
var height = screen.height
var ele = document.getElementById(main);
if(ele.style.height == "auto")
{
ele.style.height = height;
}
else {
ele.style.height = height;
}
};
If you want set the Screen Height:
var mainNode = document.getElementById("main");
mainNode.style.height = screen.height + "px";
Screen Avail Height
Screen Height
DOMElement Client Height
Screen height is different from client height (document.documentElement.clientHeight).
So, I'm using facebox to display images neatly, and I wrote a function to help with handeling the size of really big images: (fiddle: http://jsfiddle.net/LPF85/)
function open_img_in_face_box(id, width){
max_width = $j(document).width();
max_height = $j(document).height();
padding = 50;
max_width = max_width - (2 * padding);
max_height = max_height - (2 * padding);
passed_width = width || max_width;
var img = $j('#' + id);
dom_img = document.getElementById(id);
// display
jQuery.facebox({ image: img.attr('src') });
// center and adjust size
var aspect_ratio = img.width() / img.height();
var img_width = passed_width;
var img_height = passed_width / aspect_ratio;
window_center_y = max_height / 2;
window_center_x = max_width / 2;
offset_y = window_center_y - (img_height / 2);
offset_x = window_center_x - (img_width / 2);
var fbx = $j('#facebox');
fbx.css('left', offset_x + 'px !important');
fbx.css('top', offset_y + 'px !important')
$j("#facebox .image img").load(function(){
$j(this).width(img_width);
});
}
but the problem is that the image remains full size, and never gets changed to 500 (the current value I'm using for img_width).
How do I change the width of the image after it loads, but quickly enough so no one notices?
I've tested this in Chrome, and Safari with this html:
<img id="facebox_img" onclick="open_img_in_face_box('facebox_img', 500)" src="/medias/50/original.jpg" width="300" />
Here you go:
Replace:
$j("#facebox .image img").load(function(){
$j(this).width(img_width);
});
with:
$j(document).bind('reveal.facebox', function() {
$j("#facebox .image img").width(width);
})
This new code listens to the reveal event and sets the width accordingly once all the elements are in place.
Try this
$j("#facebox .image img").each(function(){
$(this).load(function(){
$j(this).width(img_width);
}).attr("src", $j(this).attr("src"));
});
How would I resize a image in jQuery to a consistent aspect ratio. For example setting maximum height and have the width resize correctly. Thanks.
Here's a useful function that might do what you want:
jQuery.fn.fitToParent = function()
{
this.each(function()
{
var width = $(this).width();
var height = $(this).height();
var parentWidth = $(this).parent().width();
var parentHeight = $(this).parent().height();
if(width/parentWidth < height/parentHeight) {
newWidth = parentWidth;
newHeight = newWidth/width*height;
}
else {
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
var margin_top = (parentHeight - newHeight) / 2;
var margin_left = (parentWidth - newWidth ) / 2;
$(this).css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
});
};
Basically, it grabs an element, centers it within the parent, then stretches it to fit such that none of the parent's background is visible, while maintaining the aspect ratio.
Then again, this might not be what you want to do.
You could calculate this manually,
i.e.:
function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}
Make sure you use the ORIGINAL values for the image otherwise it will degrade over time.
EDIT: example jQuery version (not tested)
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
var aspectRatio = $(this).data('aspectRatio');
if (aspectRatio == undefined) {
aspectRatio = $(this).width() / $(this).height();
$(this).data('aspectRatio', aspectRatio);
}
$(this).height(newHeight);
$(this).width(parseInt(newHeight * aspectRatio));
}
Use JQueryUI Resizeable
$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });
aspectRatio: true -> maintain original aspect ratio
There's no accounting for the amount of copy and pasters out there eh! I also wanted to know this and all I saw were endless examples of scaling width OR height.. who would want the other overflowing?!
Resize width AND height without the need for a loop
Doesn't exceed the images original dimensions
Uses maths that works properly i.e width/aspect for height, and height*aspect for width so images are actually scaled properly up and down :/
Should be straight forward enough to convert to javascript or other languages
//////////////
private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
double srcWidth = img.Width;
double srcHeight = img.Height;
double resizeWidth = srcWidth;
double resizeHeight = srcHeight;
double aspect = resizeWidth / resizeHeight;
if (resizeWidth > maxWidth)
{
resizeWidth = maxWidth;
resizeHeight = resizeWidth / aspect;
}
if (resizeHeight > maxHeight)
{
aspect = resizeWidth / resizeHeight;
resizeHeight = maxHeight;
resizeWidth = resizeHeight * aspect;
}
img.Width = resizeWidth;
img.Height = resizeHeight;
}
This is a good solution if you need perfect height and width aspect ratio after crop it will give perfect crop ratio
getPerfectRatio(img,widthRatio,heightRatio){
if(widthRatio < heightRatio){
var height = img.scalingHeight - (img.scalingHeight % heightRatio);
var finalHeight = height
var finalWidth = widthRatio * (height/heightRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
if(heightRatio < widthRatio){;
var width = img.scalingWidth - (img.scalingWidth % widthRatio);
var finalWidth = width;
var finalHeight = heightRatio * (width/widthRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
return img
}