swapping images of different sizes [Javascript vs IE] - javascript

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.

Related

Background image and normal image javascript loading twice

I am setting background image on div:
div.css('background-image', 'url("' + imageSrc+ '")')
But I also need to get image dimensions, so I need to load this image again:
var image = new Image();
image.src = imageSrc;
image.onload = function () {
var width = image.width,
height = image.height;
};
Does this mean this image is loading twice and its not cached as well? Is there a different way to prevent this?

Retrieve naturalWidth of updated image src

$(".photo").on('click', function(){
this.src = this.src.replace(/thumb/g, 'original');
alert(this.naturalWidth);
}
I am using jQuery in Rails4 to update the src attribute of an image. I am also using paperclip for image uploading.
The flow: when I click the image in the first time, it returns the thumb width(140px). However, the subsequent clicks return the natural width of the original image(1200px).
Is it possible to get the natural width of the original image in the first time?
Wait for the image to be loaded. onload handler will be invoked when image has finished loading
This event will fire every time src property of the image is changed.
Try this:
$(".photo").on('click', function() {
this.src = this.src.replace(/thumb/g, 'original');
var img = new Image();
img.onload = function() {
alert(this.naturalWidth);
}
img.src = this.src;
}
$(".photo").on('click', function(){
$("<img/>")
.attr("src", $(this).attr("src"))
.load(function() {
alert(this.width)
alert(this.height)
});
});

Resize HTML canvas after loading image

See http://jsfiddle.net/jdb1991/6sxke/
I've got a canvas element that doesn't know what it's going to be used for until an image has loaded, so I need to be able to change the dimensions of the element on the fly, after creating the image object.
Something is going wrong though, as it seems to be running the commands asynchronously; writing the image to the context before the resize occurs.
use:
function objectifyImage(i) {
var img_obj = new Image();
img_obj.src = i;
return img_obj;
}
var canvas = document.getElementById('display');
var context = canvas.getContext('2d');
i = objectifyImage('https://www.google.co.uk/images/srpr/logo3w.png');
i.onload = function() {
canvas.width = i.width;
canvas.height = i.height;
context.drawImage(i, 0, 0);
};
​
demo: http://jsfiddle.net/ycjCe/1/
The element can be sized arbitrarily by CSS, but during rendering the
image is scaled to fit its layout size. (If your renderings seem
distorted, try specifying your width and height attributes explicitly
in the attributes, and not with CSS.)
source: https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Basic_usage
It appears i = objectifyImage will set the image src before the image.onload handler is defined. This will cause cached images to get loaded on some browsers prior to the onload definition. Its a good idea to always define onload handlers before setting the image.src to avoid timing issues with cached images.
var self = this;
.....
this.img = document.createElement('img');
this.img.onload = function () {
self.loaded = IMGSTATE_OK;
$Debug.log('loaded image:"' + self.img.src);
}
this.img.onerror = function () {
self.loaded = IMGSTATE_ERR;
$Debug.log('error image:"' + self.img.src);
}
this.img.src = href;
..... later on check the load state

Display Image using canvas in JavaScript/jQuery

I have the following code :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Image: <img src="'+pastedImage.src+'" height="700" width="700"/>');
}
pastedImage.src = source;
}
Here I am displaying the image through html image tag which I wrote in document.write and provide appropriate height and width to image.
My question is can it possible to displaying image into the canvas instead of html img tag? So that I can drag and crop that image as I want?
But how can I display it in canvas?
Further I want to implement save that image using PHP but for now let me know about previous issue.
Try This
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here This is essential as it waits till image is loaded before drawing it.
ctx.drawImage(img , 0, 0);
};
img.src = 'myImage.png'; // Set source path
Make sure the image is hosted in same domain as your site. Read this for Javascript Security Restrictions Same Origin Policy.
E.g. If your site is http://example.com/
then the Image should be hosted on http://example.com/../myImage.png
if you try http://facebook.com/..image/ or something then it will throw security error.
Use
CanvasRenderingContext2D.drawImage.
function createImage(source) {
var ctx = document.getElementById('canvas').getContext('2d');
var pastedImage = new Image();
pastedImage.onload = function(){
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage = source;
}
Also MDN seems to be have nice examples.

Set an Image object as a div background image using javascript

I want to load 4 images from background showing a load bar to the client
and when the images will be downloaded i want to set them as background images to 4 div blocks.
I am looking for something like this.
var myImages = new Array();
for(var i = 0; i < 4; i++)
myImages[i] = new Image();
//load images using the src attribute
//and execute an on load event function where to do something like this.
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = myImage[index];
Is there any way to set a background image using an Image javascript object?
You can do something close to what you had. You don't set an image background to be an image object, but you can get the .src attribute from the image object and apply that to the backgroundImage. Once the image object has successfully loaded, the image will be cached by the browser so when you set the .src on any other object, the image will load quickly. You could use this type of code:
var imgSrcs = [...]; // array of URLs
var myImages = [], img;
for (var i = 0; i < 4; i++) {
img = new Image();
img.onload = function() {
// decide which object on the page to load this image into
// this part of the code is missing because you haven't explained how you
// want it to work
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = "url(" + this.src + ")";
};
img.src = imgSrcs[i];
myImages[i] = img;
}
The missing part of this code is deciding which objects on the page to load which image into when the image loads successfully as your example stood, you were just loading each one into the same page object as soon as they all loaded which probably isn't what you want. As I don't really know what you wanted and you didn't specify, I can't fill in that part of the code.
One thing to watch out for when using the .onload event with images is you have to set your .onload handler before you set the .src attribute. If you don't, you may miss the .onload event if the image is already cached (and thus it loads immediately).
This way, the image shows up instantly all in one once it's loaded rather than line by line.
function setBackgroundImage(){
imageIsLoaded(myURL).then(function(value) {
doc.querySelector("body > main").style.backgroundImage = "url(" + myURL + ")";
}
}
function imageIsLoaded(url){
return new Promise(function(resolve, reject){
var img = new Image();
try {
img.addEventListener('load', function() {
resolve (true);
}, false);
img.addEventListener('error', function() {
resolve (false);
}, false);
}
catch(error) {
resolve (false);
}
img.src = url;
});
}

Categories