Function to preload images? - javascript

I'm successfully pre-loading an image on my website with this JavaScript:
loveHover = new Image();
loveHover.src = "http://mypage.com/images/love-hover.png";
Is there an easy an good way to pack this thing into a function? Something like:
function preloadImage(image) {
var image = new Image();
var path = "http://mypage.com/images/";
image.src = path + image;
}

["love-hover.jpg", "like-hover.jpg", "hate-hover.jpg"].forEach(function(img)
{
new Image().src = "http://mypage.com/" + img;
});
To get this to work in IE versions earlier than 9, see the Array.forEach Compatibility section for instructions.

Well the unique part of the function would be the src (link to image). So make that the argument.
function preloadImage(src) {
var image = new Image();
image.src = src;
}
Then if you have multiple urls store them in an array:
var imageSrcs = [
"http://mypage.com/images/love-hover.png#",
"http://mypage.com/images/love-hover2.png",
"http://mypage.com/images/love-hover3.png"
];
And preload the images with a loop:
for (var i = 0; i < imageSrcs.lengthl i++)
preloadImage(imageSrcs[i]);

Have you tried not using javascript at all?
http://perishablepress.com/press/2008/06/14/a-way-to-preload-images-without-javascript-that-is-so-much-better/

Related

How to store images in an array when image is on load

I'm still new to Javascript. I have this array of images and all I want is to store it to a new array when it is onload. If it's not(onerror), it will not be stored to that new array. I already have this code wherein it shows new array that has thesame image values.
var myarray=[];
for (var i=0; i < imagesarray.length; i++) {
var image = new Image();
image.onload = function () {
console.log("Image loaded !");
myarray.push(image.src);
}
image.onerror = function () {
console.log("Cannot load image");
}
image.src = imagesarray[i].photo;
}
console.log(myarray);
Please help. Thank you. :)
Thanks to Maurice Perry.
let image= new Image() works!
This solves my problem.

Memory leak when loading images

I'm using the following code to load and resize images.
$(imagesToProcess.files).each(function (idx, file) {
var img = new Image();
img.onload = function (e) {
//var resized = _resizeImage(e.target);
URL.revokeObjectURL(e.target.src);
};
img.src = URL.createObjectURL(file);
});
This code results in a gigantic memory spike in Chrome, even though I commented out the actual resizing. What am I doing wrong?
This code, which is based on this answer, solved it for me
var fileQueue = [];
var lock = false;
var img = new Image();
img.onload = function (e) {
URL.revokeObjectURL(e.target.src);
lock = false;
};
$(imagesToProcess.files).each(function (idx, file) {
fileQueue.push(file);
});
var processQueue = setInterval(processFile, 250);
function processFile() {
if (fileQueue.length == 0) {
console.log('nothing in queue');
clearInterval(processQueue);
return;
}
if (!lock) {
img.src = URL.createObjectURL(fileQueue.shift());
lock = true;
}
}
Don't use much of anonymous functions instead use reference of the functions.
$(imagesToProcess.files).each(createImage);
function createImage(idx, file){
var img = new Image();
img.onload = imageOnload;
img.src = URL.createObjectURL(file);
}
function imageOnload(e) {
URL.revokeObjectURL(e.target.src);
}
In you code for every image creation one instance of function object is created. That is what causing memory leak in your code.
I ended up solving this memory leak in my program by using an alternate method of jpeg-decoding (using library rather than browser's Image object): https://stackoverflow.com/a/62584068/2441655

Javascript, load an image only if it exists

I've a series of folders containing images numbered sequentially (1.jpg, 2.jpg, 3.jpg… etc).
I'm trying to load the images with a for loop until the first non existing image is found.
I read some other article managing similar problem (check if an image exists) with onload and onerror callback functions, but I'm stuck.
Here there is some code I wrote to store the images in an array and display them in the HTML page along with their src:
var arrImages = new Array();
function loadImgSeq() {
for (var i = 0; i < 11; i++) {
arrImages[i] = new Image();
arrImages[i].src = "slides/" + i + ".jpg"
arrImages[i].width = 400;
document.body.appendChild(arrImages[i]);
document.write("<p>"+arrImages[i].src+"</p>");
}
}
PS:I've no experience in computer programming, I just do it as hobbyist.
Here's one:
var found = true;
while(found)
{
var img = new Image();
img.src = 'path';
found = img.naturalWidth? true : false;
}
do not document.write after load
do not mix append with document.write
Here is a way
var i=0,img;
function loadImgSeq() {
i++;
var img = new Image();
img.onload=function() {
document.body.appendChild(img);
loadImgSeg(); // if success, do it again - will not be called if error
}
img.src = "slides/" + i + ".jpg";// IMPORTANT, must be AFTER onload/onerror handler
}
UPDATE: If you get IE issues from cache, try
img.onload=img.complete=function() {

this code gives 0 as height and width for the first time it iterates and the second time gives the right dimensions

var icon1 = new Image();
icon1.src = resource;
var width = icon1.width;
var height = icon1.height;
This code when iterates gives 0 as width and height for the first time it iterates and for the second time it gives right dimensions.
You haven't really shown enough code (and general context) to be sure, but I'd wager that the first time, the image hasn't loaded, and the second time, it has.
You can make sure the image has loaded first via the onload event.
var resource = "http://placehold.it/50";
var icon1 = new Image();
var wid1;
var hei1;
icon1.onload = function() {
wid1 = icon1.width;
hei1 = icon1.height;
console.log(wid1);
console.log(hei1);
};
icon1.src = resource;
try assigning the resource to the src before defining the onload function.
var resource = "http://placehold.it/50";
var icon1 = new Image();
var wid1;
var hei1;
icon1.src = resource;
icon1.onload = function() {
wid1 = icon1.width;
hei1 = icon1.height;
console.log(wid1);
console.log(hei1);
};

How to fetch a remote image to display in a canvas?

How can I fetch images from a server?
I've got this bit of code which allows me to draw some images on a canvas.
<html>
<head>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
for (i=0;i<document.images.length;i++){
ctx.drawImage(document.images[i],i*150,i*130);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canv" width="1024" height="1024"></canvas>
<img src="http://www.google.com/intl/en_ALL/images/logo.gif">
<img src="http://l.yimg.com/a/i/ww/beta/y3.gif">
<img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png">
</body>
</html>
Instead of looping over document.images, i would like to continually fetch images from a server.
for (;;) {
/* how to fetch myimage??? */
myimage = fetch???('http://myserver/nextimage.cgi');
ctx.drawImage(myimage, x, y);
}
Use the built-in JavaScript Image object.
Here is a very simple example of using the Image object:
myimage = new Image();
myimage.src = 'http://myserver/nextimage.cgi';
Here is a more appropriate mechanism for your scenario from the comments on this answer.
Thanks olliej!
It's worth noting that you can't synchronously request a resource, so you should actually do something along the lines of:
myimage = new Image();
myimage.onload = function() {
ctx.drawImage(myimage, x, y);
}
myimage.src = 'http://myserver/nextimage.cgi';
If you want to draw an image to a canvas you also need to wait for the image to actually load, so the correct thing to do will be:
myimage = new Image();
myimage.onload = function() {
context.drawImage(myimage, ...);
}
myimage.src = 'http://myserver/nextimage.cgi';
To add an image in JavaScript you can do the following:
myimage = new Image()
myimage.src='http://....'
If an image on your page has an ID "image1", you can assign the src of image1 to myimage.src.
I have found that using prototypes is very helpful here. If you aren't familiar with them, prototypes are part of objects that allow you to set your own variables and/or methods to them.
Doing something like:
Image.prototype.position = {
x: 0,
y: 0
}
Image.prototype.onload = function(){
context.drawImage(this, this.position.x, this.position.y);
}
allows you to set position and draw to the canvas without too much work.
The "position" variable allows you to move it around on the canvas.
So it's possible to do:
var myImg = new Image();
myImg.position.x = 20;
myImg.position.y = 200;
myImg.src = "http://www.google.com/intl/en_ALL/images/logo.gif";
and the image will automatically draw to the canvas at (20,200).
Prototype works for all HTML and native Javascript objects. So
Array.prototype.sum = function(){
var _sum = 0.0;
for (var i=0; i<this.length; i++){
_sum += parseFloat(this[i]);
}
return _sum;
}
gives a new function to all Arrays.
However,
var Bob;
Bob.Prototype.sayHi = function(){
alert("Hello there.");
}
will not work (for multiple reasons, but i'll just talk about prototypes).
Prototype is a "property" of sorts, which contains all the your properties/methods that you input, and is already in each of the HTML and native Javascript objects (not the ones you make).
Prototypes also allow for easy calling (you can do "myImg.position.x" instead of "myImg.prototype.position.x" ).
Besides, if you are defining you variable, you should do it more like this.
var Bob = function(){
this.sayHi = function(){
alert("Hello there.");
}
}
Using Promises:
class App {
imageUrl = 'https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4HZBo'
constructor(dom) {
this.start(dom)
}
async start(dom) {
const appEl = dom.createElement('div')
dom.body.append(appEl)
const imageEl = await this.loadImage(this.imageUrl)
const canvas = dom.createElement('canvas')
canvas.width = imageEl.width
canvas.height = imageEl.height
const ctx = canvas.getContext('2d')
ctx.drawImage(imageEl, 0, 0)
appEl.append(canvas)
}
loadImage = async (url) =>
new Promise((resolve) => {
const imageEl = new Image()
imageEl.src = url
imageEl.onload = () => resolve(imageEl)
})
}
new App(document)
If you are using jQuery you can do:
$.('<img src="http://myserver/nextimage.cgi" />').appendTo('#canv');
You can also add widths and anything else in the img tag.

Categories

Resources