How can I load an array of images to be faded? - javascript

I have the following code where I am loading only one image. But I want to load multiple images from e folder and then to fade them in and out. But what I am interesting in, is how can I load all images from a folder without to repeat the code, as src="frames/frame_1" src="frames/frame_2" i want something soft as src="frames/frame_" + i + ".jpg" where i is the number of the frame
this is how I load only one image now
var img = new Image();
var div = document.getElementById('foo');
img.onload = function() {
div.appendChild(img);
};
img.src = 'frames/frame_1.jpg';

It's relatively simple. You basically put the code you already had in a loop:
var img, i,
imageCount = 5,
div = document.getElementById('foo');
for(i = 0; i < imageCount; i++){
img = new Image();
img.onload = function() {
div.appendChild(img);
};
img.src = 'frames/frame_' + i + '.jpg';
}

You can use a loop for :
var img,
div = document.getElementById('foo');
for (var i = 0, nbImg = 5; i < nbImg; i++) {
img = new Image();
img.onload = function() {
div.appendChild(img);
};
img.src = 'frames/frame_'+i+'.jpg';
}

Related

JavaScript array for an image gallery with next and prev functions

var spanishAdventure = new Array();
spanishAdventure[0] = new Image();
spanishAdventure[0].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756508_1743696655674610_7179458580676129491_o.jpg?_nc_cat=0&oh=f16a2edf4ee735e66b6dab095b7fb43c&oe=5B6B32B3';
spanishAdventure[1] = new Image();
spanishAdventure[1].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26758659_1743696569007952_4447096103197624856_o.jpg?_nc_cat=0&oh=a7f015a6709fa9a26f06b07fe9782999&oe=5B6A180E';
spanishAdventure[2] = new Image();
spanishAdventure[2].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678421_1743695449008064_7298258449829506874_o.jpg?_nc_cat=0&oh=d8fb71ad599a0a630f4d118c1d8be6ca&oe=5B6E0AFD';
spanishAdventure[3] = new Image();
spanishAdventure[3].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678110_1743696009008008_4042393389305650172_o.jpg?_nc_cat=0&oh=7d6afafd399c4a2d5d8f0747d59d8353&oe=5B73557C';
spanishAdventure[4] = new Image();
spanishAdventure[4].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756324_1743697449007864_8430059194945119796_o.jpg?_nc_cat=0&oh=5c93856d22087dbf550fc98dfd7a79ce&oe=5B5FBF15';
spanishAdventure[5] = new Image();
spanishAdventure[5].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678350_1743697612341181_2805503461338827658_o.jpg?_nc_cat=0&oh=1e6d3b0c44b783742de688cedacccc20&oe=5B6E31BF';
spanishAdventure[6] = new Image();
spanishAdventure[6].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26841396_1743696739007935_7256143030060966136_o.jpg?_nc_cat=0&oh=d0b9cbe4f3920af54083ea12d2d19b40&oe=5B63A5E7';
var imageCount = 0;
var totalImage = spanishAdventure.length -1; //array length starting from 0
var img = document.getElementById('mySlides'); //HTML img element which image will be displayed
function imagePrev() {
imgCount-- ;
img.src =spanishAdventure[imageCount].src;
if (imageCount < 0) {
img.src = spanishAdventure[totalImage].src;
break;
}
}
function imageNext() {
imgCount++ ;
img.src =spanishAdventure[imageCount].src;
if (imageCount > totalImage) {
img.src = spanishAdventure[0].src;
break;
}
}
Hi Guys,
I'm currently trying to create an image gallery using Javascript image array and functions that will be called upon to create a gallery in an image element in my original HTML file (not shown). Do you see anything wrong with the js syntax and code for the next and previous functions as they seem to not work when called upon in the html file. I'm a newbie so some enlightening pointers would be fab.
mySlides is the id for an HTML img element.
Cheers,
Liam
As #Titus said, change imageCount to imgCount, or vice-versa
Remove break; from imagePrev and imageNext. It's not doing anything useful.
Build logic to keep imageCount (or imgCount) within the range of your image array.
You don't need to instantiate images to store your source urls. The urls are just text, so they could be put directly into an array, like spanishAdventure = ['urlText1', 'urlText2', ...]
var spanishAdventure = new Array();
spanishAdventure[0] = new Image();
spanishAdventure[0].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756508_1743696655674610_7179458580676129491_o.jpg?_nc_cat=0&oh=f16a2edf4ee735e66b6dab095b7fb43c&oe=5B6B32B3';
spanishAdventure[1] = new Image();
spanishAdventure[1].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26758659_1743696569007952_4447096103197624856_o.jpg?_nc_cat=0&oh=a7f015a6709fa9a26f06b07fe9782999&oe=5B6A180E';
spanishAdventure[2] = new Image();
spanishAdventure[2].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678421_1743695449008064_7298258449829506874_o.jpg?_nc_cat=0&oh=d8fb71ad599a0a630f4d118c1d8be6ca&oe=5B6E0AFD';
spanishAdventure[3] = new Image();
spanishAdventure[3].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678110_1743696009008008_4042393389305650172_o.jpg?_nc_cat=0&oh=7d6afafd399c4a2d5d8f0747d59d8353&oe=5B73557C';
spanishAdventure[4] = new Image();
spanishAdventure[4].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756324_1743697449007864_8430059194945119796_o.jpg?_nc_cat=0&oh=5c93856d22087dbf550fc98dfd7a79ce&oe=5B5FBF15';
spanishAdventure[5] = new Image();
spanishAdventure[5].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678350_1743697612341181_2805503461338827658_o.jpg?_nc_cat=0&oh=1e6d3b0c44b783742de688cedacccc20&oe=5B6E31BF';
spanishAdventure[6] = new Image();
spanishAdventure[6].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26841396_1743696739007935_7256143030060966136_o.jpg?_nc_cat=0&oh=d0b9cbe4f3920af54083ea12d2d19b40&oe=5B63A5E7';
var imageCount = 0;
var totalImage = spanishAdventure.length -1; //array length starting from 0
var img = document.getElementById('mySlides'); //HTML img element which image will be displayed
function imagePrev() {
imageCount > 0 ? imageCount-- : imageCount = 6;
img.src =spanishAdventure[imageCount].src;
}
function imageNext() {
imageCount < 6 ? imageCount++ : imageCount = 0;
img.src =spanishAdventure[imageCount].src;
}
<img id="mySlides" />
<button onClick="imagePrev()">Prev</button>
<button onClick="imageNext()">Next</button>

Create a function to add an image to an array on click of button

I have a web page that displays an array of images of world leaders.
I need to add a button that will add an additional leader onto that array and display it as well.
If anyone could point me in the right direction, thanks in advance.
<button class="btn" id="addLeader">Add Leader</button>
</section>
<script type="text/javascript">
window.onload = function () {
var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg']; //array of images
ArrayOfImages.forEach(function (image) { // for each link l in ArrayOfImages
var img = document.createElement('img'); // create an img element
img.src = image; // set its src to the link l
img.height = '300';
img.width = '200';
img.hspace = '20';
document.body.appendChild(img); // append it to the body
});
var addButton = document.getElementById('addLeader');
addButton.addEventListener('click', addLeader);
}
function addLeader(){
ArrayOfImages.push('images/kimjongun.jpg');
console.log(ArrayOfImages);
}
</script>
If you turn the display part into a function you can call it to re-render. I made a simple and naive version.
var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg']; //array of images
function displayImages (images) {
images.forEach(function (image) { // for each link l in ArrayOfImages
var img = document.createElement('img'); // create an img element
img.src = image; // set its src to the link l
img.height = '300';
img.width = '200';
img.hspace = '20';
document.body.appendChild(img); // append it to the body
});
}
var addButton = document.getElementById('addLeader');
addButton.addEventListener('click', addLeader);
displayImages(ArrayOfImages);
function addLeader(){
ArrayOfImages.push('images/kimjongun.jpg');
document.body.innerHTML = ''; //clear previous images
displayImages(ArrayOfImages);
}

how to make a variable of two variables

Before your read this, my first account was blocked because i asked bad questions.. So please dont vote negative but say what i am doing wrong
Sooo I have this script:
var img1 = new Image()
img1.src="image1.jpg"
var img2 = new Image()
img2.src="image2.jpg"
var img3 = new Image()
img3.src="image3.jpg"
function Canvas() {
var ctx = document.getElementById('slider').getContext('2d');
var pic=1
function slider() {
this.draw = function() {
if(pic<4){pic++}
else{
pic=1
}
var img = "img"+pic
ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height)
}
}
var slider = new slider();
function draw() {
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.save();
//draw
slider.draw();
//draw
ctx.restore();
}
var animateInterval = setInterval(draw,100)
}
window.addEventListener('load', function(event) {
Canvas();
});
I am trying to draw the image 1 or 2 or 3 on my canvas. But I also have the var pic wich has the number. So i tried ctx.drawimage(img+pic,0,0) or var img = "img"+pic and draw it then. But it doesnt work for me.
I hope you accept my question and can answer it, THNX
Use an array instead
var img = [];
/* you should use a for loop here */
for (var i = 0; i < 3; i++) {
img[i] = new Image();
img[i].src = "image" + (i+1) ".jpg";
}
and later you refer the right image with img[pic]. Be only sure to use an index between 0 and img.length - 1
Don't use separate variables, use an array.
var images = [ new Image(), new Image(), new Image() ];
for (var i = 0; i < images.length; i++) {
images[i].src = "image" + (i+1) + ".jpg";
}
Then refer to the array in the Slider() function:
var pic = 0;
function slider() {
this.draw = function() {
pic = (pic + 1) % images.length;
var img = images[pic];
ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height)
}
}
The error seems to be that you refer to the string "img1" and not the object img1. Try use an array instead.
Set the following:
...
var pic=0;
var img=[img1,img2,img3];
function slider() {
this.draw = function() {
if(pic<3){pic++}
else{
pic=0;
}
ctx.drawImage(img[pic],0,0,ctx.canvas.width,ctx.canvas.height)
}
}
...

Canvas to data url not working properly

I have a function that takes an img-element and returns a data url. This works like 7/10 times and returns a blank image 3/10 times. I view the created data url through my browser(chrome) and use the same images so I know that this function is returning broken images. Can anyone spot why?
function imgToDataURL(img) {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var c = canvas.getContext('2d');
c.drawImage(img, 0, 0);
dataurl = canvas.toDataURL();
return dataurl;
}
$(function() {
img = new Image();
img.crossOrigin = '';
img.onload = function() {
newimg = new Image();
newimg.onload = function() {
document.body.appendChild(newimg);
}
newimg.src = imgToDataURL(img);
}
img.src = 'https://somedomain.s3.amazonaws.com/someimg.png';
});
This example works most of the time but sometimes ends with a large white rectangle instead of the image.
You have to wait for images to load before drawing them using .drawImage function.
Only after the image is loaded by the browser you can call your imgToDataURL function.
Something like this:
var image_sources = ["img1.png", "img2.png", "..."];
for(var i=0; i<image_sources.length; i++) {
var new_img = document.createElement("img");
new_img.onload = function() {
imgToDataURL(this);
};
new_img.src = image_sources[i];
}

getImageData always returning 0

I have been trying to make a script that compares two images in HTML5 and Javascript. But for some odd reason, it always returns that the images are completely the same.
And when looking at what the problem could be, I found out that every data value of every pixel returned, for some odd reason, "0".
So, any idea of what I have done wrong? :)
For some reason I feel like it's something very simple, but I just learned about the canvas element, so yeah.
This is my code:
function compareImg() {
var c1 = document.getElementById("c");
var ctx1 = c1.getContext("2d");
var c2 = document.getElementById("c2");
var ctx2 = c2.getContext("2d");
var match = 0;
var img1 = new Image();
img1.src = "cat.jpg";
img1.onload = function() {
ctx1.drawImage(img1, 0, 0);
}
var img2 = new Image();
img2.src = "bird.jpg";
img2.onload = function() {
ctx2.drawImage(img2, 0, 0);
}
for(var x = 0; x<c1.width; x++) { // For each x value
for(var y = 0; y<c1.height; y++) { // For each y value
var data1 = ctx1.getImageData(x, y, 1, 1);
var data2 = ctx2.getImageData(x, y, 1, 1);
if (data1.data[0] == data2.data[0] && data1.data[1] == data2.data[1] && data1.data[2] == data2.data[2]) {
match++;
}
}
}
var pixels = c1.width*c1.height;
match = match/pixels*100;
document.getElementById("match").innerHTML = match + "%";
}
You are not waiting until your images have loaded and drawn before performing your comparison. Try this:
var img = new Image;
img.onload = function(){
ctx1.drawImage(img,0,0);
var img = new Image;
img.onload = function(){
ctx2.drawImage(img,0,0);
// diff them here
};
img.src = 'cat.jpg';
};
img.src = 'cat.jpg';
As shown above, you should always set your src after your onload.
I suspect that the problem is that your image data is probably not ready at the point you try to use it for the canvas. If you defer that code to the onload handlers, that will (probably) help:
var img1 = new Image(), count = 2;
img1.src = "cat.jpg";
img1.onload = function() {
ctx1.drawImage(img1, 0, 0);
checkReadiness();
}
var img2 = new Image();
img2.src = "bird.jpg";
img2.onload = function() {
ctx2.drawImage(img2, 0, 0);
checkReadiness();
}
function checkReadiness() {
if (--count !== 0) return;
for(var x = 0; x<c1.width; x++) { // For each x value
for(var y = 0; y<c1.height; y++) { // For each y value
var data1 = ctx1.getImageData(x, y, 1, 1);
var data2 = ctx2.getImageData(x, y, 1, 1);
if (data1.data[0] == data2.data[0] && data1.data[1] == data2.data[1] && data1.data[2] == data2.data[2]) {
match++;
}
}
}
var pixels = c1.width*c1.height;
match = match/pixels*100;
document.getElementById("match").innerHTML = match + "%";
}
All I did was add a function wrapper around your code. That function checks the image count variable I added, and only when it's zero (i.e., only after both images have loaded) will it do the work.
(This may be superstition, but I always assign the "onload" handler before I set the "src" attribute. I have this idea that, perhaps only in the past, browsers might fail to run the handler if the image is already in the cache.)
Now another thing: you probably should just get the image data once, and then iterate over the returned data. Calling "getImageData()" for every single pixel is going to be a lot of work for the browser to do.

Categories