I have a page with a list of items where each item has a square div containing a background image. This image can have dimensions which are either bigger, or smaller than the div itself. The background centered and contained in the div so it is always shown in the middle of the div.
The css for this is as follows:
.productImage
{
width: 225px;
height: 225px;
background-size: contain;
background-position: center center;
background-repeat: no-repeat;
margin-left:70px;
}
The background-image itself is set using a jQuery call that modifies the css of the div.
This works like charm, however I would like to know the dimensions of the rendered background image. If the rendered is smaller than a specific dimension I would like to set a background color for aesthetic reasons.
I am currently unable to retrieve the dimensions of the rendered images. I have used the following code in a loop to try and retrieve the dimensions of the images, but this returns the original dimensions of the images, before they have been scaled into the div.
images[i] = new Image();
images[i].src = $('#image'+i).css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
images[i].pos = i;
images[i].onload = function() {
var position = this.pos;
width = this.width;
height = this.height;
console.log("For image "+position+" the height is "+height+" and width is "+ width);
}
How would I be able to find out the dimensions of the rendered background image using jQuery or pure Javascript? Is this even possible?
Thanks in advance.
After playing with Huangism's idea a bit I came to the following solution:
images[i] = new Image();
images[i].src = $('#image'+i).css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
images[i].pos = i;
images[i].onload = function() {
var position = this.pos;
width = this.width;
height = this.height;
var divwidth = $('#image'+position).width();
var divheight = $('#image'+position).height();
var ratioH = divheight / height;
var ratioW = divwidth / width;
var scaleW = width * ratioH;
var scaleH = height * ratioW;
console.log("For image "+position+" the height is "+height+" and width "+ width +" and ratioH "+ratioH + " and ratioW " + ratioW +" (Scaled width: "+scaleW+")" );
if(scaleW < 120 || scaleH < 100){
$('#image'+position).css('background-color', 'red');
}
}
This code compares the image used as a background image's height and width with the dimensions of the div he is contained in. Based on this I calculate the scaling ratio between the original height and width and the maximum height and width within the div.
This ratio is then multiplied with the opposing dimension (height * width ration, width * height ratio) to calculate the dimensions of the rendered image.
Comparing the values in the console to measurements in Photoshops shows they are a perfect match!
I hope this answer can help other users that want to know the dimensions of a rendered background image.
Give the image an id then:
var width = document.getElementById('myImageID').offsetWidth;
var height= document.getElementById('myImageID').offsetHeight;
Related
I'm getting an image's binary data as an ArrayBuffer, and inserting it into a document using docx.js:
getImageBinaryDataAsArrayBuffer().then(function (imageBuffer) {
var doc = new docx.Document();
var image = docx.Media.addImage(doc, imageBuffer);
doc.addSection({
children: [
new docx.Paragraph({
children: [image],
alignment: docx.AlignmentType.CENTER
}),
]
});
docx.Packer.toBlob(doc).then(function (blob) {
// save the doc somewhere
})
}).catch(function (err) {
console.log(err);
});
This works, but it seems like the image size is defaulting to 100x100, and is not preserving the aspect ratio. In the docx.js documentation for Images, it looks like you can specify the height and width when you add the image to the doc:
Media.addImage(doc, [IMAGE_BUFFER], [WIDTH], [HEIGHT], [POSITION_OPTIONS]);
but I don't know the image's natural height and width since all I'm working with is an ArrayBuffer. (Can you determine an image's height and width from ArrayBuffer data? My gut says no...)
Is there a way to tell docx.js to use the image's natural height and width? Or at least to preserve the aspect ratio?
You can get the image dimension from the binary format as well. Here is my code which preserves aspect ratio when you need to resize the image to specific width/height
import imageSize from 'image-size'; // https://www.npmjs.com/package/image-size
function fitImage(doc, image, targetWidth?, targetHeight?) {
const originalSize = imageSize(image);
const originalAspectRatio = originalSize.width / originalSize.height;
let width: number;
let height: number;
if (!targetWidth) {
// fixed height, calc width
height = targetHeight;
width = height * originalAspectRatio;
} else if (!targetHeight) {
// fixed width, calc height
width = targetWidth;
height = width / originalAspectRatio;
} else {
const targetRatio = targetWidth / targetHeight;
if (targetRatio > originalAspectRatio) {
// fill height, calc width
height = targetHeight;
width = height * originalAspectRatio;
} else {
// fill width, calc height
width = targetWidth;
height = width / originalAspectRatio;
}
}
console.log(originalSize, originalAspectRatio, width, height);
return Media.addImage(doc, image, width, height);
}
const image = fitImage(doc, imageBuffer, 100); // set width to 100px calc height
const image = fitImage(doc, imageBuffer, null, height); // set height to 100px calc width
const image = fitImage(doc, imageBuffer, 100, 100); // fit image inside a 100x100 box
I am new one to canvas concept,I am trying to draw canvas using D3.js. I want to make canvas as responsive based on window screen size.
function onResize(){
var element = document.getElementsByTagName("canvas")[0];
var context = element .node().getContext("2d");
var scrnWid = window.innerWidth,
scrnHgt = window.innerHeight,
elementHgt = element.height,
elementWid = element.width;
var aspWid = elementWid/scrnWid;
var aspHig = elementHgt/scrnHgt;
context.scale(aspWid,aspHig);
}
window.addEventListener("resize",onResize);
This is the code I used to resize canvas, but it not working.I don't want to use any library except D3.js. Can anyone suggest me better solution ?
2DContext.scale() changes rendered content not display size / resolution
You are not changing the canvas size, all you are doing is scaling the content of the canvas.
You can set the page size of the canvas via its style properties
canvas.style.width = ?; // a valid CSS unit
canvas.style.height = ?; // a valid CSS unit
This does not affect the resolution (number of pixels) of the canvas. The canvas resolution is set via its width and height properties and is always in pixels. These are abstract pixels that are not directly related to actual device display pixels nor do they directly relate to CSS pixels (px). The width and height are numbers without a CSS unit postfix
canvas.width = ?; // number of pixel columns
canvas.height = ?; // number of pixel rows
Setting the 2D context scale has no effect on the display size or the display resolution, context.scale(?,?) only affects the rendered content
To scale a canvas to fit a page
const layout = { // defines canvas layout in terms of fractions of window inner size
width : 0.5,
height : 0.5,
}
function resize(){
// set the canvas resolution to CSS pixels (innerWidth and Height are in CSS pixels)
canvas.width = (innerWidth * layout.width) | 0; // floor with |0
canvas.height = (innerHeight * layout.height) | 0;
// match the display size to the resolution set above
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
}
I've seen a few posts here trying to answer this question and I tried using the codes given as answers but haven't been able to get it to work, so I must be doing something wrong. Basically I have a div with a background-image with the CSS property "background-size: contain". I want to get the dimensions of the scaled background. Here is my code, mostly copied from another post here, with some things changed to match my div's names:
var elem = document.querySelector("#enlarged-inner .image-bg");
function getBackgroundSize(elem) {
elem = document.querySelector("#enlarged-inner .image-bg");
//get original background size
var computedStyle = getComputedStyle(elem);
var img = new Image;
img.src = computedStyle.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2');
var imgW = parseInt(img.width, 10);
var imgH = parseInt(img.height, 10);
//get scaled size
var newW = parseInt(computedStyle.width, 10);
var newH = parseInt(computedStyle.height, 10);
var scaledW = 0;
var scaledH = 0;
scaledW = imgW / imgH * newH;
scaledH = imgH / imgW * newW;
}
window.onresize = function(){ getBackgroundSize(elem); }
Its able to get the original (unscaled) size of the background image just fine, so I atleast know that the first half of the code is working. But the second part, the important part, doesn't seem to do anything. I've been testing it by changing a test divs innerHTML to the new variables:
document.getElementById("test").innerHTML = newW + " , " + newH;
I'm new to javascript and not great at math so I'm sure theres probably something I'm just not understanding correctly here.
EDIT: the code above has been updated a little and heres some more explanation.
So in this picture the blue box is a scalable div that contains the div with the background. Its height and width are set with vh and vw.
The gray box represents the background image itself, with its size set to contain. In the updated code above, newW and newH give me the dimensions of the blue box, no matter how its scaled. imgW and imgH give me the original unscaled dimensions of the background. I want scaledW and scaledH to return the scaled size of the gray box, but my math doesnt seem to work out.
I can't test it right now but I think that the variables you're modifying (newW and newH) are passed by value. So, you actually don't update your image's size. You'll probably need to use these variables to update your image's size, maybe with:
img.width = newW etc
I figured out a simpler way to achieve what I wanted. Basically what I was trying to do was have a div with an image in it, that I could scale to any size, and the entire image would always fit inside the div (similar to the background-size contain property), and the images would always maintain their original aspect ratio. In my particular case instead of a div, its the size of the full window, and I found it to be easier to work with images in img tags instead of backgrounds. Heres the code:
function getBackgroundSize(elem) {
elem = document.querySelector("#enlarged-inner img");
var imgW = elem.naturalWidth;
var imgH = elem.naturalHeight;
var newW = window.innerWidth;
var newH = window.innerHeight;
var imgRatio = imgW / imgH;
var newRatio = newW / newH;
var scaledW = 0;
var scaledH = 0;
if (imgRatio > newRatio) {
scaledW = newW;
scaledH = imgH * newW / imgW; }
else {
scaledW = imgW * newH / imgH;
scaledH = newH; }
document.querySelector("#enlarged-inner img").style.width = scaledW;
document.querySelector("#enlarged-inner img").style.height = scaledH;
}
I basically just found the unscaled height and width of the image, and the dimensions of the containing div (the window in my case), and then found their ratios of width over height. I'm not so good at math but atleast in the examples I tried to work out, if the W/H of the image was larger than W/H of the window, it would mean the image's width would be defined by the width of the window. And then the correct height of the image could be found with some simple math.
So i have a gallery where most my images are currently controlled 100% by CSS. However, in setting min-height: 100%; on my images, i cause some to stretch. I don't have too many problematic photos, but it's out of my control what the user will upload.
Is there anyway with jQuery i can get image height and check if it's meeting a requirement, and if not, somehow increase the image width in order to meet the height requirement but keep things all in ratio? So i therefore avoid causing any distortion but keep the gallery neat by having divs without gaps.
Note: The image provided is what happens when i remove my min-height: 100%; so that you can see my issue.
Update - - - - -
I found a solution that seems to work ok for the moment, it might not be the best attempt but i found another answer that helped me: How to resize images proportionally / keeping the aspect ratio?
I simply tweaked the code ever so slightly, now if an image doesn't meet the minHeight required it will resize the image in proportion so until the minHeight is then reached. Seems work fine for me in testing.
**Update Final *********
After playing around i took a small snippit from the thumb script, just the part where it absolutely positions the images within the container.
$(window).load(function() {
$('.thumbnail img').each(function() {
var maxWidth = 320; // Max width for the image
var minHeight = 270; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height < minHeight){
ratio = minHeight / height; // get ratio for scaling image
$(this).css("height", minHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
var $img = $(this),
css = {
position: 'absolute',
marginLeft: '-' + ( parseInt( $img.css('width') ) / 2 ) + 'px',
left: '50%',
top: '50%',
marginTop: '-' + ( parseInt( $img.css('height') ) / 2 ) + 'px'
};
$img.css( css );
});
});
This loops through all my thumbnails, resizes them accordingly. So if the minimum height is not met, the image will be scaled up until the height fits my thumbnail container. Then the bottom part will take take each image, absolutely position it, and take the width and height and divide by 2, in order to work out how much to minus off on the margins to center the image. I'm still tweaking this, but seems to work well for me at the moment. I hope this helps someone else.
Alternatively
Anyone with a similar issue i found this: http://joanpiedra.com/jquery/thumbs/ I had begun writing my own to do exactly this, but im going to look into how well this works and adapt it as needed.
I found a solution that seems to work ok for the moment, it might not be the best attempt but i found another answer that helped me: How to resize images proportionally / keeping the aspect ratio?
Updated question with my findings
$(window).load(function() {
$('.image-gallery-item-image-link img').each(function() {
var maxWidth = 320; // Max width for the image
var minHeight = 270; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height < minHeight){
ratio = minHeight / height; // get ratio for scaling image
$(this).css("height", minHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
var $img = $(this),
css = {
position: 'absolute',
marginLeft: '-' + ( parseInt( $img.css('width') ) / 2 ) + 'px',
left: '50%',
top: '50%',
marginTop: '-' + ( parseInt( $img.css('height') ) / 2 ) + 'px'
};
$img.css( css );
});
});
well, if keeping the entire picture visible isn't necessary(e.g. thumbnails in a gallery), you could accomplish this with css only. it seems you have landscape type photos.
html
<div class="img-container">
<img src="path/to/img.png" alt="">
</div>
css:
div > img {
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width:100%;
height:100%;
}
jquery:
$(document).ready(function(){
$(".imgcontainer > img").each(function(){
var thisimg = "url("+$(this).attr('src')+")";
$(this).css({'background-image': thisimg });
$(this).attr('src', '');
});
});
Whose aspect ratio you are talking about ? aspect ratio of your gallery or the aspect ratio of the image ? You can't keep an image in correct aspect ratio by changing one dimension only (here height). In order to keep aspect ratio, you must change both the height and width of the image. Any way if you want try this :
var img = document.getElementById('imageid');
var width = img.clientWidth;
var height = img.clientHeight;
if(width >height)
$(img).attr('style',"width=100%");
else
$(img).attr('style',"height=100%");
What I am trying to do is that, set the css of the largest dimension to 100%. It'll do the trick.
So, I realize this question asked a while ago. But I've since found a sweet css only way to maintain the aspect ratio of an element, fluidly. Try it out:
#targetElement {
max-width: 100%;
}
#targetElement:after {
content: '';
width: 100%;
padding-bottom: <aspect-ratio>%; // where (height / width)*100 = <aspect-ratio>
}
Yeah, so I use this trick all the time now, and it's definitely more performant and less verbose than using javascript, or even less efficient, JQuery. Hope this helps somebody somewhere! If you're a LESS person, I have a mixin Gist on Github that does this -- that's how often I use it! It lives here: Sweet AR trick.
Looks like I haven’t explained myself well. I do apologize for that.
I have edited this question to make it more clear.
The scenario
We have a website that doesn’t host the images. What it does is a reference to an image in other server.
The plan
Resize images keeping proportions.
Center resized images.
Flexible so it can fit in several sizes.
The bug
My code works as intended, however there is a Bug that only happens sometimes.
If you go to the search page of the website, and swap between page 1, 2, 3 and 4 a couple of times, you will notice that sometimes the images are good… other times they appear aligned left, and do not take up the full container area.
The links
The full website (in beta)
The JavaScript File
The jQuery plugin that helped me (jThumb)
The plan (detailed version)
Let’s say that the image is 600x400 pixels (remember they are not hosted on this server), and with jQuery and CSS, I want to resize the image (keeping proportions) in to a container of 310x200 pixels.
The other challenge is to center the image.
All this has to be flexible because there are several different containers sizes in the website.
What I have done so far (you can find this in the link above)
To resize the image I'm doing:
var img = new Image();
img.src = $(this).attr("src");
var width = $(this).css('width');
var height = $(this).css('height');
var photoAspectRatio = img.width / img.height;
var canvasAspectRatio = width.replace("px", "") / height.replace("px", "");
if (photoAspectRatio < canvasAspectRatio) {
$(this).css('width', width);
$(this).css('height', 'auto');
var intHeight = height.replace("px", ""); //tirar o PX
$(this).css('marginTop', (-Math.floor(intHeight / 2)));
}
else {
$(this).css('width', 'auto');
$(this).css('height', height);
}
$(this).wrap('<div class="thumb-img" style="width:' + width + ' ;height:' + height + ';"><div class="thumb-inner">' + '</div></div>');
To center the image I’m doing:
jQuery(this).css('position','absolute');
jQuery(this).left( '-' + ( parseInt( $(this).width() ) / 2 ) + 'px' );
jQuery(this).top( '-' + ( parseInt( $(this).height() ) / 2 ) + 'px' );
jQuery(this).css('margin-left', '50%' );
jQuery(this).css('margin-top', '50%');
There's a far simpler solution to determine how to resize and position the image. It will work with all image and container sizes.
var canvasWidth = parseInt(width);
var canvasHeight = parseInt(height);
var minRatio = Math.min(canvasWidth / img.width, canvasHeight / img.height);
var newImgWidth = minRatio * img.width;
var newImgHeight = minRatio * img.height;
var newImgX = (canvasWidth - newImgWidth) / 2;
var newImgY = (canvasHeight - newImgHeight) / 2;
Now just position the image using newImgX, newImgY, and resize it to newImgWidth, newImageHeight.
This is probably a race condition. You are setting the img src and then immediately trying to get its width and height attributes. But there is no guarantee that the web browser has downloaded the image or pulled it from the browser cache yet, and if it hasn't, your code will lead to unexpected results.
You need to do something like this:
var img = new Image();
var $thumb = $(this);
img.load(function() {
/* .....[image calculation and resize logic]..... */
});
img.src = $thumb.attr("src");
Note that the order of the above statements is very important -- you must attach the img.load event handler first, then assign the img.src second. If you do it in the other order, you will end up with an opposite race condition (the image may already be loaded after the img.src assignment, in which case the event handler will not be called in all browsers -- by setting the event handler first you ensure that it will be called after the img.src assignment even if the image is already loaded).
Also, note the $thumb definition at the top. This is because "this", inside the img.load function, will be a reference to the new "img", not the thumbnail element. So your logic will have to reference "$thumb" for the DOM element and "this" (or "img") for the in-memory image.
Also, for the actual logic take a look at the answer "Scott S" provided above. His suggestion looks simpler than what you have.
It's not clear from your question, but I'm assuming one your issues is the left-align of the images in the table at the bottom half of your front page at http://www.algarvehouses.com.
The issue here is not your jQuery code, rather it is your CSS.
add a text-align: center to your thumb-inner class. Then make sure that rule is loaded AFTER the "table.dlRandom img, ..." rule - or remove the display:block from that rule. That should center those images.
Generally though - to scale the image, your logic looks correct up to the point of the div. Don't quite understand that logic. You don't need to set the auto size though, just restrain the dimension that is required.
One tangential tip - in the code above you reference $(this) no less than 16 times. Do this at the top of the function, and use it from there on:
var $this = $(this);
I really didn't get your question but this maybe be help you.
function resizer(imgCls, maxWidth, maxHeight) {
var img = $('img'), imgWidth, imgHeight;
img.each(function () {
imgWidth = this.width;
imgHeight = this.height;
if (imgWidth > maxWidth || imgHeight > maxHeight) {
var widthFact = maxWidth / imgWidth;
var heightFact = maxHeight / imgHeight;
var chooseFact = (widthFact > heightFact) ? heightFact : widthFact;
imgWidth = imgWidth * chooseFact;
imgHeight = imgHeight * chooseFact;
}
})
}
this code gets the images matches the provided className and looks your arguments. pass maxWidth to your maxWidth value such as 300 px, and pass maxHeight to your images maxHeight such as 300.
then the function will loop for every image and checks its width and height. If its width or height is larger than your max values then it will be resized by keeping the aspect ratio.
Please let you free to ask more question about the issue and please be more clear.
This script will shrinks, and align image depending of their orientation. Image is rounded with div ho has fixed width and hight, and also a style set to overflow:hidden. The script actual recognize the image orientation and ad to image a margin-left or margin-top in minus atribute to style depending of a image vertical or horizontal orientation.
CSS:
<style type="text/css">
.thumb {
width:160px;
height:160px;
overflow:hidden;
}
</style>
jquery with javascript:
window.onload = function() {
var images = $(".image_center");
for(i=0; i<images.length; i++)
images[i].onload = centerImage(images[i]);
function centerImage(img) {
if (img.width > img.height ) {
var y = 160;
var x = img.width/img.height*y;
var marx = (x-y)/2;
img.style.height = y+"px";
img.style.marginLeft = -(marx) + "px";
}
if (img.width < img.height ) {
var x = 160;
var y = img.height/img.width*x;
var mary = (y-x)/2;
img.style.width = x+"px";
img.style.marginTop = -(mary) + "px";
}
}
}
HTML:
<div class="thumb"><img class="image_center" src="sa.jpg" alt="#" /></div>
<div class="thumb"><img class="image_center" src="sb.jpg" alt="#" /></div>
You can see demo here: Link
Another useful plugin which achieves this is jQuery Center Image which supports two modes. One to fill the entire space by cropping and resizing the image and another which emulates max-width/max-height to resize to fit within the space.