I am trying to preload images using Javascript. I am to suppose to use onload function and modularized coding. I have the codes below, but it does not seem to work. Any suggestions would greatly be appreciated. Thanks in advance.
function preloadImages() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
img1.src = "images/banner1.jpg";
img2.src = "images/banner2.jpg";
img3.src = "images/banner3.jpg";
}
}
function addLoadEvent(func) {
var loadImages = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function() {
if (loadImages) {
loadImages();
}
func();
};
}
}
addLoadEvent(preloadImages);
I don't really know what you're trying to do. Perhaps this can help?
function ImgMaker(basePath){
this.img = function(url, doneFunc, errorFunc){
var img = new Image();
var b = basePath ? basePath.replace(/(\\|\/)$/) : '';
if(doneFunc)img.onload = doneFunc;
if(errorFunc)img.onerror = errorFunc;
img.src = b+url;
return img;
}
}
var doc, bod, im = new ImgMaker;
function noError(){
console.log(this.src+' loaded');
}
function error(){
console.log(this.src+" did't load");
}
addEventListener('load', function(){
doc = document; bod = doc.body;
bod.appendChild(im.img('img1.png', noError, error));
bod.appendChild(im.img('img2.png', noError, error));
bod.appendChild(im.img('img3.png', noError, error));
bod.appendChild(im.img('img4.png', noError, error));
bod.appendChild(im.img('img5.png', function(){
console.log(this.src+' loaded'); // showing anonymous way
// want async? load another image here
}, function(){
console.log(this.src+" didn't load");
}));
}); // end load
Related
I am new to coding in javascript, I have been tasked as an excersise using some pre-existing functions to create an image item using a given url. I need to read the image, store it in local storage and then display it on the screen. The only functionI need to add too is process file. I am stuck and cannot get it to display the image. I get an error saying that the path does not exist. Below is my code, any guidance to what I am doing wrong? I feel like I am very close but doing something funamendatly wrong.
function addImageEntry(key, url) {
var imgElement = new Image();
imgElement.alt = "Photo entry";
imgElement.src = url;
addSection(key, imgElement);
}
function makeItem(type, data) {
var itemObject = { type: type, data: data };
return JSON.stringify(itemObject);
}
function processFile(event) {
function addImage(url) {
var key = "diary" + Date.now();
addImageEntry(key, url);
var imgElement = new Image();
imgElement.src = url;
var item = makeItem("image", imgElement.src);
localStorage.setItem(key, item);
}
var inputElement = event.target;
var fileObject = inputElement.files[0];
var reader = new FileReader();
reader.addEventListener("load",addImage);
url = reader.readAsDataURL(fileObject);
event.target.value = "";
}
The url = reader.readAsDataURL(fileObject) won't store the image data.
It stores in reader.result.
Use imgElement.src = reader.result.
document.querySelector('input[type="file"]').addEventListener('change', processFile)
function processFile(event) {
var fileObject = event.target.files[0]
var reader = new FileReader()
reader.addEventListener('load', addImage)
reader.readAsDataURL(fileObject)
function addImage() {
var imgElement = new Image()
imgElement.src = reader.result
document.body.append(imgElement)
}
}
Amend:
function addImage(event) {
// use reader.result is ok too
localStorage.setItem('myimage', event.target.result)
}
function addImageEntry() {
var imgElement = new Image()
imgElement.src = localStorage.getItem('myimage')
imgElement.style.display = 'block'
document.body.append(imgElement)
}
Hello me need get variable from function
me return in answer undefined
function etr() {
var img = new Image();
img.onload = paramsImg;
img.src = picFile.result;
function paramsImg() {
return img.height;
};
};
var vvvr = etr();
alert(vvvr);
function etr() {
var img = new Image();
img.onload = paramsImg;
img.src = picFile.result;
function paramsImg() {
return img.height;
};
};
In your function, you mentioned paramsImg before its even loaded, so its not visible to img.onload.
paramsImg is declared simply as function, its not have scope outside the object. You need to use this keyword or mention fn with prototype.
function etr(picFile){
this.paramsImg = function(){
return img.height;
};
var img = new Image();
img.onload = this.paramsImg;
img.src = picFile.result;
}
picfile = {
result: 10
}
var vvvr = new etr(picfile);
alert(vvvr.paramsImg());
Your function etr doesn't return anything. I see that you are trying to return from an event handler for onload, but that only returns from the paramsImg function and not from etr (which has already returned before the image loads). You should wither make etr accept a callback function or return a Promise so that you can alert the images height after the image has loaded. Here is an example with a Promise:
function etr() {
return new Promise( ( resolve, reject ) => {
var img = new Image();
img.onload = _ => resolve(img.height);
img.onerror = reject;
img.src = picFile.result;
} );
};
var picFile = { result: 'https://dummyimage.com/600x1234/000/fff' };
(async function ( ) {
var vvvr = await etr();
alert(vvvr);
})( );
Basically I have two images that i need to display at the same time(and more later).
var Canvas = function(canvasEl, width, height){
this.el= canvasEl;
this.el.width = width;
this.el.height = height;
this.ctx = canvasEl.getContext("2d");
}
var canvas = new Canvas(document.querySelector("#mycanvas"), 1100, 650);
var add = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 500,-215);
};
add.src="add.png";
var currentdate = new Date();
var datetime = currentdate.getHours();
if(datetime==1||datetime==13){
var clock1 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock1.png";
}
else if(datetime==2||datetime==14){
var clock2 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock2.png";
}
else if(datetime==3||datetime==15){
var clock3 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock3.png";
}
else if(datetime==4||datetime==16){
var clock4 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock4.png";
}
else if(datetime==5||datetime==17){
var clock5 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock5.png";
}
else if(datetime==6||datetime==18){
var clock6 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock6.png";
}
else if(datetime==7||datetime==19){
var clock7 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock7.png";
}
else if(datetime==8||datetime==20){
var clock8 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock8.png";
}
else if(datetime==9||datetime==21){
var clock9 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock9.png";
}
else if(datetime==10||datetime==22){
var clock10 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 600,100);
};
add.src="clock/clock10.png";
}
else if(datetime==11||datetime==23){
var clock11 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock11.png";
}
else if(datetime==12||datetime==0){
var clock12 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock12.png";
}
</script>
</body>
I have that currently and all it is supposed to do is have one image named "add.png" and another (based on the time) called "clock.png" to display at the same time in different locations on the canvas. The code works but it only shows the clock.
You need a separate .onload for each image--not just 1 add.onload
// not always add.onload ...
add.onload ... add.src="add.png";
clock1.onload ... clock1.src="clock/clock1.png";
clock2.onload ... clock2.src="clock/clock2.png";
// same for clock3-12
Keep in mind that images are loaded asynchronously, so the load order of your images is not guaranteed to be the same as your code. That may or may not be a problem depending on how the images fit together.
Here's an example of an image loader that guarantees all images are loaded and that the images are all in your specified order:
// image loader
var imageURLs=[];
var imagesOK=0;
var imgs=[];
imageURLs.push("add.png");
imageURLs.push("clock/clock1.png");
imageURLs.push("clock/clock2.png");
imageURLs.push("clock/clock3.png");
imageURLs.push("clock/clock4.png");
imageURLs.push("clock/clock5.png");
imageURLs.push("clock/clock6.png");
imageURLs.push("clock/clock7.png");
imageURLs.push("clock/clock8.png");
imageURLs.push("clock/clock9.png");
imageURLs.push("clock/clock10.png");
imageURLs.push("clock/clock11.png");
imageURLs.push("clock/clock12.png");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds your fully loaded images
// the imgs[] are in the same order as imageURLs[]
}
Objekt.prototype.loadImg = function(pImg){
if(pImg!=null){
this.imgLoaded=false;
this.img = null;
this.img = new Image();
this.img.src = pImg;
this.img.onload = function(){
alert("!");
this.autoSize();
this.imgLoaded=true;
};
}
}
My Problem is that "this" is invalid in the "onload = function()"-function!
alert("!"); is executed, but not the Objekt.prototype.autoSize()-function for example!
What do I have to do to call my "class-intern"-functions (e.g. autoSize) ???
That's because the onload function isn't called with your objekt as receiver. So this, inside this callback, isn't the desired object.
You can do this to transmit this to the onload callback :
Objekt.prototype.loadImg = function(pImg){
if(pImg!=null){
this.imgLoaded=false;
this.img = null;
this.img = new Image();
this.img.src = pImg;
var _this = this;
this.img.onload = function(){
alert("!");
_this.autoSize();
_this.imgLoaded=true;
};
}
}
This is a jquery plugin that i've found, that creates an img element and appends it to a parent element.
$.fn.loadImg = function(src, f){ return this.each(function(){ var i = new Image(); i.src = src; i.onload = f; this.appendChild(i);}); }
How can i add paramaters attrName, attrVal to the function that would assign whatever attributes to the image before appending it?
This should work:
$.fn.loadImg = function(src, f, attrName, attrVal) {
return this.each(
function() {
var i = new Image();
i.src = src;
i.onload = f;
i[attrName] = attrVal;
// alternatively:
// i.setAttribute(attrName, attrVal);
this.appendChild(i);
}
);
}