I have an image that is being resized programmatically, based on the current height/width of the container. My problem is that it shows the image at it's original size before it does the resizing.
See this JSFiddle
You'll notice how it flashes up a stretched image before it fits the image nicely in the middle.
I want to hide the image until that resizing has taken place, but I can't figure out how.
Any suggestions?
JSCode:
function LoadImg(img) {
img.css('visibility','hidden');
var src=img.attr('src');
var imgh = img.parent().height();
var imgw = img.parent().width();
var pattern = /&?(w|h)=[^&]+/g;
src = src.replace(pattern, '');
img.attr('src', src + '&w=' + imgw + '&h=' + imgh);
img.css('visibility','');
}
Html:
<div class="window">
<img src="http://www.angclassiccarparts.co.uk/image_anysize.aspx?f=/images/ww/panel/service_kits.jpg&w=154&h=154&color=png" id="img" onload="LoadImg($(this));" />
</div>
I've tried hiding with visibility hidden until the function has run, but that doesn't wait for it to load...
You're changing the source of the image, which forces it to load a new image, then you instantly set the image to visible.
Ultimately you want to wait until the second image is loaded before showing it, which can be achieved using .load() like so:
img.on('load', function() {
img.css('visibility','visible');
});
Here's an updated jsFiddle with the working code: http://jsfiddle.net/ev4YL/2/
I would, however, recommend a different approach. It doesn't make much sense to load an image, then when it's loaded load another image. Perhaps you should store the dimensions in html data attributes, then load the images dynamically on document.ready.
Something like this could work, if you set each image to have a data-src instead of src to begin with:
$('img').each(function() {
var img = $(this);
var src = img.attr('data-src');
var imgh = img.parent().height();
var imgw = img.parent().width();
var pattern = /&?(w|h)=[^&]+/g;
src = src.replace(pattern, '');
img.attr('src', src + '&w=' + imgw + '&h=' + imgh);
img.on('load', function() {
img.css('visibility','visible');
});
});
And the demo here: http://jsfiddle.net/ev4YL/4/
You can hide the image with display: none until the end of the function, then set the image to display: block (or whatever you need) at the very end. That way the rest of the function has already run, when it displays it will have already been resized.
See JSFiddle
But basically just:
CSS:
img {
display: none;
}
JavaScript:
function loadImg(img) {
----all of your function here----
img.css('display', 'block');
}
Related
I am having a jQuery script that loads 15 images and their hover versions (the hover versions are used when... hovering, not when the page loads). In both Chrome and Firefox in the Network tab, i see this :
images/img1.png
images_hover/img1.png
This must mean the hover images are preloaded correctly, but... when i actually hover and those images are used, they are being loaded again. Here is the preload code :
var prel = new Image();
prel.src = "http://hdodov.byethost15.com/color-game/graphics/parts_hover/" + id + ".png";
I tried using the whole path - http://hdodov.byethost15.com/color-game/graphics/parts_hover/ and the short path too (where the root and the script is) - graphics/parts_hover/. It made no difference.
Could this be caused because my images have the same name? They are in different directories though.
For the next question, you really should paste more code, which makes it easier to help you. I checked your URL you provided, but for other people that might have the same problem, it will be hard to understand what went wrong...
OK, as I said, you are always requesting he images again on hover state...
This worked for me:
var context = new Array(15),
canvas = new Array(15),
canvasNum = -1,
hElem,
hElemPrev,
mousePos = {x:-1, y:-1},
images = [], //<-- Store preloaded images here
imagesHover = []; //<-- Store preloaded images here
... then save them on building like this:
function drawMenuItems(id, width, height){
var canNumHolder, createCanvas;
$('#canvas_holder').append($('<canvas></canvas>')
.attr({
width:width,
height:height,
id:id
})
);
canvasNum++;
canvas[canvasNum] = document.getElementById(id);
context[canvasNum] = canvas[canvasNum].getContext('2d');
canNumHolder = canvasNum;
images[id].crossOrigin = 'Anonymous';
images[id].onload = function(){
context[canNumHolder].drawImage(images[id],0,0);
};
images[id].src = 'graphics/parts/' + id + '.png';
//Hover states
imagesHover[id] = new Image();
imagesHover[id].src = "graphics/parts_hover/" + id + ".png";
}
... give just the id...
function hoverStateChange() {
//....rest of the code
if(hElem >= 0){
drawImageOnCanvas(
canvas[hElem],
context[hElem],
"hover", //pass somethink to checke what you want to do
$(canvas[hElem]).attr('id')
);
//....rest of the code
//change to normal texture
if(hElemPrev >= 0){
drawImageOnCanvas(
canvas[hElemPrev],
context[hElemPrev],
"", //pass empty for other state
$(canvas[hElemPrev]).attr('id')
);
$(canvas[hElemPrev]).removeClass('active');
$('#text_holder').removeClass('a' + hElemPrev);
}
.. and finally
function drawImageOnCanvas(canv, contxt, state, src){
contxt.clearRect(0,0,400,400);
if(state == "hover"){
contxt.drawImage(imagesHover[src],0,0);
}else {
contxt.drawImage(images[src],0,0);
}
}
Like this, you chache you images and not calling them again and again...
I hope it helps.
Yuo can preload images with css like this:-
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
This code switches the background between two different images. However when it switches from the first image to the second there is always a one second buffer before the image gets displayed and this only happens the very first time the images switch. How can I get rid of the buffer?
function changeBgColor(){
var img = ['url(img/mechanic.jpg)', 'url(img/start.jpg)'];
var nImg = img.length;
var currentImg = 0;
document.body.style.backgroundImage = "url(img/start.jpg)";
document.body.style.backgroundSize = "cover";
document.body.style.backgroundRepeat = "no-repeat";
var imgChange = setInterval(function(){
document.body.style.backgroundImage = img[currentImg];
document.body.style.backgroundSize = "cover";
document.body.style.backgroundRepeat = "no-repeat";
if(currentImg == nImg-1){
currentImg = -1;
}
currentImg++;
},10000);
}
This will be due to the loading of image. Once the image is loaded it is cached and therefore the problem is not evident after first load. To combat this you could preload the images in question using CSS or jquery
CSS
body:after{
display:none;
content: url(img01.png) url(img02.png) url(img03.png) url(img04.png);
}
jQuery
<script>
pic = new Image();
pic2 = new Image();
pic3 = new Image();
pic.src="images/inputs/input1.png";
pic2.src="images/inputs/input2.png";
pic3.src="images/inputs/input3.png";
</script>
It will be due to the image needing to load. The second time it switches the browser has already stored it in the cache. You need to let the image load before displaying it.
Can you put the two images into separate divs, and toggle making one visible / the other hidden? That should remove the delay when you switch between the two.
My user can upload really big images, and for cropping and display purposes i'm adding width attribute so it will fit well in the browser window. Real image size can be - say 1920 x 1080 px.
<!-- width added for display purpose -->
<img class="croppable" src="images/fhd.jpg" width="640" />
In order to calculate real selection box dimension (if the x coordinate is 20px then would be 60px in the original full hd picture) i need to get the full image size before apply the width attribute.
The problem is that this will return 640 as value, taking into account the width attribute:
// Important: Use load event to avoid problems with webkit browser like safari
// when using cached images
$(window).load(function(){
$('img.croppable').each(function(){
alert(this.width);
});
});
Please don't flag this as duplicate since what i'm asking is completly different from simple image width/height retrival (which works, actually).
EDIT: Chris G. solution seems not working:
$(window).load(function(){
$('img.croppable').each(function(){
console.log(this.src);
var original = new Image(this.src);
console.log(original);
$("#original_w").text(original.width); // Temp, more images to be added
$("#original_h").text(original.height); // Temp, more images to be added
});
});
Console output:
http://localhost/DigitLifeAdminExtension/images/pillars-of-creation.jpg
<img width="0">
Get the width/height of the image itself, not the div it is contained within.
$(window).load(function(){
$('img.croppable').each(function(){
var img = new Image();
img.src = $(this).src;
alert(img.width);
});
});
You can remove the attributes, get the width and put the attributes in place again:
var $img = $(img);
var oldWidth = $img.attr("width");
var imgWidth = $img.removeAttr("width").width();
$img.width(oldWidth);
But I think Chris G.'s answer works well too, just making sure it will be loaded when you try to get the width:
img.onload = function() {
if (!img.complete) return; // IMG not loaded
width = img.width;
imgManipulationGoesHere();
}
Works in most up-to-date browsers and IE9.
$(window).load(function(){
$('img.croppable').each(function(){
alert(this.naturalHeight);
});
});
The working solution would be:
$(function(){
$('img.croppable').each(function () {
var original = new Image(this.src);
original.onload = function () {
alert(original.src + ': ' + original.width + 'x' +original.height);
};
});
});
I've read about various kinds of ways getting image dimensions once an image has fully loaded, but would it be possible to get the dimensions of any image once it just started to load?
I haven't found much about this by searching (which makes me believe it's not possible), but the fact that a browser (in my case Firefox) shows the dimensions of any image I open up in a new tab right in the title after it just started loading the image gives me hope that there actually is a way and I just missed the right keywords to find it.
You are right that one can get image dimensions before it's fully loaded.
Here's a solution (demo):
var img = document.createElement('img');
img.src = 'some-image.jpg';
var poll = setInterval(function () {
if (img.naturalWidth) {
clearInterval(poll);
console.log(img.naturalWidth, img.naturalHeight);
}
}, 10);
img.onload = function () { console.log('Fully loaded'); }
The following code returns width/height as soon as it's available. For testing change abc123 in image source to any random string to prevent caching.
There is a JSFiddle Demo as well.
<div id="info"></div>
<img id="image" src="https://upload.wikimedia.org/wikipedia/commons/d/da/Island_Archway,_Great_Ocean_Rd,_Victoria,_Australia_-_Nov_08.jpg?abc123">
<script>
getImageSize($('#image'), function(width, height) {
$('#info').text(width + ',' + height);
});
function getImageSize(img, callback) {
var $img = $(img);
var wait = setInterval(function() {
var w = $img[0].naturalWidth,
h = $img[0].naturalHeight;
if (w && h) {
clearInterval(wait);
callback.apply(this, [w, h]);
}
}, 30);
}
</script>
One way is to use the HEAD request, which asks for HTTP Header of the response only. I know in HEAD responses, the size of the body is included. But I don't know if there anything available for size of images.
I have the following simple preloading function which substitute an image "src" attribute with another image (an animated GIF "Loading"). The problem arises only in IE: if the "loading" GIF is smaller than the actual image src, that will be resized. For example if I have a square 100px image and preload it, the image is temporarly substituted by an animated GIF of 50x50px. Whem the original image is fully loaded it is NOT displayed at its size, but at the smaller 50px. Here is the code, if you need it
_preload = function(url, placeholderUrl) {
var img = new Image();
loading = true;
var placeholder = new Element("img", {
src: placeholderUrl
});
img.placeholder = placeholder;
img.onload = function(evt) {
this.placeholder.src = this.src;
loading = false;
}
img.src = url;
return placeholder;
}
Here you can see the visual error
You should be able to adjust the width/height of the image within the callback function:
img.onload = function(evt) {
this.placeholder.src = this.src;
this.placeholder.width = this.width;
this.placeholder.height = this.height;
loading = false;
}
Example: Resizing image onLoad
I guess replacing placeholder with img (the img-elements inside the dom), instead of simply changing the src-attribute of placeholder, should fix this issue.