Cycling between two images - javascript

// this code is meant to create an array of two images and just circle through them to make it appear that a lightbulb is flashing on and off.
var imageArray = new Array();
var numImages=2;
// create new array to hold preload images; call this array imageArray
// create (global!) variable called numImages to hold total number of images;
//use for loop to populate imageArray
for (var i = 0; i < numImages; i++) {
imageArray[i] = new image();
imageArray[i].src="images/brightIdea"+(i+1)+"png"
//set image src property to image path, preloading image in the process
}
var i4_circleThru = 0; // global variable ( be careful) use for the function CicleThru()
function circleThru() {
//if browser does not support the image object, exit.
// write images, from imageArray to HTML doc
// call the setTimeout method on circleThru
}//end circleThru()

Because your end result is an html image, why not do it this way:
First, in your HTML:
<img id="imageID">
Then in your script:
var imageArray = [];
var numImages = 2;
for (var i = 0; i < numImages; i++) {
imageArray[i] ="images/brightIdea"+(i+1)+".png"
}
var i4_circleThru = 0;
var image = document.getElementById("imageId");
image.src = imageArray[i4_circleThru];
window.setInterval(function(){
i4_circleThru = (i4_circleThru+1)%numImages;
image.src = imageArray[i4_circleThru];
},1000);
A more complete example can be found here:
https://jsfiddle.net/FrancisMacDougall/fseswsro/

Related

Looping through all the images on a page

2 Questions:
What will be the most officiant way to loop through all of the Images on a given page and open each one in a new tab.
Same idea but instead open in a new tab I would like to push different images instead of the given ones. The idea is to build a widget that will inject cat photos instead of the normal photos of websites.
I answered 2 in the code, and 1 in the comment of the first code block
var allImages = document.getElementsByTagName('img');
for(var i = 0; i < allImages.length ; i++) {
// to open all photos in new tabs:
// window.open(allImages[i].src, '_blank');
allImages[i].src = 'url_to_cat_image';
}
you can also do the same with jquery:
// change all photos to the same one:
var allImages = $('img');
allImages.attr('src', 'url_to_cat_image');
If you want each photo to be a different image, just replace the url_to_cat_image with a function that returns a random cat image in the first code block. For jquery, you can use .each and a random cat url function.
Here's a way of doing it with vanilla js. As mentioned in the comments, using the document.images node-list is the best method for getting the images, since it's a static list and need not be assembled in response to dom queries.
As mentioned, browsers will block the attempts to open new windowss, labelling them as pop-ups.
Here's a demo:
function forEachNode(nodeList, func) {
for (var i = 0, n = nodeList.length; i < n; i++) func(nodeList[i], i, nodeList);
}
function onBtnClicked() {
var diskUrl =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC" +
"3RAAABdElEQVQoU22SLX/CMBCH/3E4IueorKNysh+hH6ESR93mqBuOuuEWiYyczB" +
"zycJPBIa+uU9nvmlD2wonmLulz78q+c4DIMH7Hk0UfOJ5/75KtrOWg9RxEwHqdfr" +
"xz9F9AXX9Ag8fXG3jssX6a3yUFwtCjqgnsDbK8gjIHDtnDHM6dsdks/oFXSNKuVg" +
"5VXoA+HZQxHLJsDvt+xu7lN/gTYgbqxqHMM3hPUGbvQ5YvYO0Ju91yivgX4oETWI" +
"AvBNV1PhTFAuZwwttrBO9B0u2qkVSzBG4jKL2yhxNYtDSSmx5HM0LyxgTVthEUkT" +
"qY+2mO0cHVUZrrOF8P1T5TKIpl8tTDHdvfnZ0BeqbBXN6WYiCoRsB8OUUiamEPHY" +
"qyhNlbYAZ0+w6eirRFUpSHapoIeu5Hj/TZwV8I5WOFZlUn0MA5DS3lANCSarOikE" +
"nRzDBHAi4dum1MV1IcI25beK6mvdUgKLHqlQsCSsRJpAlXIzUomvH+G/9qC1CEZi" +
"AJAAAAAElFTkSuQmCC";
forEachNode(document.images, function(elem) {
elem.oldSrc = elem.src;
console.log(elem.src);
window.open(elem.src);
elem.src = diskUrl
});
}
function onResetBtn() {
forEachNode(document.images, function(elem) {
if (elem.oldSrc != undefined) elem.src = elem.oldSrc;
});
}
<button onclick='onBtnClicked()'>Open pop-ups, change image sources</button>
<button onclick='onResetBtn();'>Reset</button>
<br>
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAHCAYAAAAvZezQAAAAKElEQVQIW2MUder+/3pfKSMDFDCCBEBsmCBcACaIIgASxK0CxQxkWwA6axnpT9J3PwAAAABJRU5ErkJggg==' />
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAHCAYAAAAvZezQAAAAJElEQVQIW2NkQAKiTt3/GWF8EAfEBgvAOGABZA52FVjNQBYEAPsjDS+SFXnjAAAAAElFTkSuQmCC' />
This is how you loop through all the images in a page.
I've also added example of opening in a new tab or replacing the source.
using native JavaScript no dependencies required.
// Array of cat photos
var arr = ['cat1.jpg', 'cat2.jpg', 'cat3.jpg'....]
var elem = document.getElementsByTagName('img');
for (var i = 0; i < elem.length; i++) {
var src = elem[i].getAttribute('src');
// Open in a new tab
if (src) window.open(src);
// Replace with a random cat photo
elem[i].src = arr[Math.floor(Math.random() * arr.length)];
}
Using vanilla javascript :
var images = document.querySelectorAll("img");
for(var i = 0;i < images.length;i++){
var image = images[i];
window.open(image.src,"_blank");
}
// changing for a kitty image
var images = document.querySelectorAll("img");
for(var i = 0;i < images.length;i++){
var image = images[i];
image.src = "http://placekitten.com/600/338";
}
However, if there are more than 1 image the browser will prevent that (see the popup message and allow that behaviour).

Javascript image array issue

this is my problem: im trying to create an image selector, i mean a collection of images shown on the screen among which i can choose one and store it in a var. This is the code for the array:
<script typre="text/javascript">
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
for (var i = 0; i < img.length; i++) {
document.write(img[i]);
};
</script>
When i run it, it displays [object HTMLImageElement] instead of the image! What should i do?? Thanks all!
Because img[i] is an object and document.write will write it as string representation of it by calling img[i].toString().
If you want to display an image then use
for (var i = 0; i < img.length; i++) {
document.body.appendChild(img[i]);
};
var img = new Image();
img.src = "../images/poggiatesta2.jpg";
document.write(img.outerHTML);
Use the outerHTML property in order to display it
It is obvious because for loop will print img[0],img[1] not src of image
You can write img[i].src
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
for (var i = 0; i < img.length; i++) {
alert(img[i].src);
};

passing value from javascript to partial view in mvc

the given below is my script
var selectedImage;
function select(image) {
var images = document.querySelectorAll('img');
var index = 0, length = images.length;
for (; index < length; index++) {
images[index].classList.remove('selected');
}
selectedImage = image.id;
image.classList.add('selected');
var image = document.getElementById(selectedImage);
var audioId = image.getAttribute('data-audio')
var audioElement = document.getElementById(audioId);
}
Now i want to pass the value of "audio element (which contains the Url of an audio fetched from database)" to another function which is defined in partial view. How to do this? please help.

Cannot set property 'src' of null in JavaScript

I'm in the middle of changing some existing javascript code which exports images inside a HTML document to a word document. The new functionality is going to capture canvas data inside HTML, convert it to .png and then export however I'm getting 'Cannot set property 'src' of null' when the code reaches this part:
//Capture all canvas data
var canvasData = markup.find('canvas');
var tempImage = new Image();
////Array to hold of the images
var imageArray = Array();
for (var i = 0; i < canvasData.length; i++) {
tempImage.src = canvasData[i].toDataURL("image/png");
imageArray[i] = tempImage;
tempImage = null;
}
Any help would be greatly appreciated!
As you can see you are nullifying tempImage inside the loop, after the first iteration it will be assigned a null value, so in the next iteration you'll be trying to set the src for null. that is why you are getting this error. Take var tempImage = new Image(); inside the loop.
for (var i = 0; i < canvasData.length; i++) {
var tempImage = new Image();
tempImage.src = canvasData[i].toDataURL("image/png");
imageArray[i] = tempImage;
tempImage = null;
}
Move your var tempImage = new Image(); to inside the loop. Something like
for (var i = 0; i < canvasData.length; i++) {
var tempImage = new Image();
tempImage.src = canvasData[i].toDataURL("image/png");
imageArray[i] = tempImage;
// not really required
// tempImage = null;
}

how to use drawImage after load all images in array

I want to draw image array with drawImage after all the images are loaded.There is a render problem with drawImage(), tried to solve with setTimeout() but its not working all the time.
Here is my code;
while(FocusItem.length>0)
{
FocusItem.pop();
}
ftx=canvas.getContext('2d');
focusImageBackground = new Image();
focusImageBackground.src = "./images/odaklanma/odaklanmaBackground.jpg";
if(RandomSoru==15)
finishSoru=true;
if(finishSoru)
{
RandomSoru = Math.floor((Math.random() * 15)+1);
tempRandomSoru=RandomSoru;
}
if(RandomSoru==tempRandomSoru)
{
RandomSoru = Math.floor((Math.random() * 15)+1);
}
var soru = new Object();
soru["image"] = new Image();
soru.image.src = './images/odaklanma/level/'+RandomSoru+'/soru.png';
soru["x"] = 341;
soru["y"] = 140;
FocusItem.push(soru);
var dogru = new Object();
dogru["image"] = new Image();
dogru.image.src = './images/odaklanma/level/'+RandomSoru+'/dogru.png';
dogru["x"] = xDogru;
dogru["y"] = 280;
FocusItem.push(dogru);
var yanlis = new Object();
yanlis["image"] = new Image();
yanlis.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis.png';
yanlis["x"] = xYanlis1;
yanlis["y"] = 280;
FocusItem.push(yanlis);
var yanlis2 = new Object();
yanlis2["image"] = new Image();
yanlis2.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis1.png';
yanlis2["x"] = xYanlis2;
yanlis2["y"] = 280;
FocusItem.push(yanlis2);
}
if(focusImageBackground.complete){
if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
drawFocus();
else
setTimeout(drawFocus,600);
}
else
focusImageBackground.onload=function(){
if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
drawFocus();
else
setTimeout(drawFocus,600);
}
function drawFocus(){
ftx.drawImage(focusImageBackground,0,0);
for (var i=0; i<FocusItem.length; i++){
FocusItem[i].image.onload=function(){
ftx.drawImage (FocusItem[i].image, FocusItem[i].x, FocusItem[i].y);
}
}
}
I'd suggest loading all your images, then when they are all done, you can call the rest of your code. I don't quite follow what you're trying to do with all the rest of your code, but here's a simple way to load an array of image URLs and know when they are done.
This is the general idea (I've left out lots of your code that has nothing to do with the central issue of knowing when all the images are loaded) and I've also tried to DRY up your code:
function createImagesNotify(srcs, fn) {
var imgs = [], img;
var remaining = srcs.length;
for (var i = 0; i < srcs.length; i++) {
img = new Image();
imgs.push(img);
img.onload = function() {
--remaining;
if (remaining == 0) {
fn(srcs);
}
};
// must set .src after setting onload handler
img.src = srcs[i];
}
return(imgs);
}
// here's your starting array of filenames
var fnames = ["soru.png", "dogru.png", "yanlis.png", "yanlis1.png"];
// insert your process to create RandomSoru here
var randomSoru = ....;
// build full urls array
var urls = [];
for (var i = 0; i < fnames; i++) {
urls.push('./images/odaklanma/level/' + RandomSoru + '/' + fnames[i]);
}
// load all images and call callback function when they are all done loading
var imgs = createImagesNotify(urls, function() {
// all images have been loaded here
// do whatever you want with all the loaded images now (like draw them)
});
This code is based on an earlier answer of mine here: Cross-browser solution for a callback when loading multiple images?

Categories