Trouble changing images with a timer with javascript - javascript

I am writing a website and I want to animate through various images on a timer. I have an array listing each of the images (as a number which is used to build the filename). The animation should go through those numbers and in turn change the image. This code is not working and any help would be appreciated.

<img id="myImg" src=" http://old.ycombinator.com/images/yc500.gif" width ='100' height='100'/>
<script>
var myImages = [1, 2, 3, 5]
var img_index = 0;
var timer;
var imgId = "myImg";
// Bind the image onload event like this:
document.getElementById(imgId).onload = animate();
// Start animation
function animate() {
me = document.getElementById(imgId);
me.src = "coolimg." + myImages[img_index] + ".jpg"
img_index++;
if (img_index == myImages.length){
img_index = 0;
}
timer = setTimeout(animate, 1000);
}
</script>

Related

Get random images when clicking on image for javascript

I am currently learning Javascript, and I was able to create a simple game where the shapes and color will change and it will move around. I am stuck on how to input images...please help me!! =( Thank you! =)
This is the site to the game I created http://sites.codeschool.org.uk/?site=imat3ap0t
I want to change the shapes to 3 jpg pictures I have and have it do the same thing. I am so stuck!
function getRandomColor() {
var letters = '0123456789ABCDEF'.split(''); //the numbers&letters are for color codes. split is the string (set of numbers and letters into an array)
var color = '#'; //color codes start with #
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 16)];
}
return color;
}
var clickedTime;
var createdTime;
var reactionTime;
function makeBox() {
var time = Math.random();
time = time * 5000;
setTimeout(function () {
if (Math.random() > 0.5) {
document.getElementById("box").style.borderRadius = "100px";
} else {
document.getElementById("box").style.borderRadius = "0";
}
var top = Math.random();
top = top * 300;
var left = Math.random();
left = left * 500;
document.getElementById("box").style.top = top + "px";
document.getElementById("box").style.left = left + "px";
document.getElementById("box").style.backgroundColor = getRandomColor();
document.getElementById("box").style.display = "block";
createdTime = Date.now();
}, time);
}
document.getElementById("box").onclick = function () {
clickedTime = Date.now();
reactionTime = (clickedTime - createdTime) / 1000;
document.getElementById("time").innerHTML = reactionTime;
document.getElementById("box").style.display = "none";
makeBox();
}
makeBox();
Thank you guys for the response!
Well you will need to modify your function to something like this:
function getRandomImage() {
// All of the image options
// This is very similar to string of characters you have now
var images = ['path/to/image/1', 'path/to/image/2', 'path/to/image/3']
// Randomly select one image path
// By using images.length we don't have to hardcode the length like the "16" you're using, which is good incase the list changes
var imagePath = images[Math.floor(Math.random() * images.length)];
// Return random image path
return imagePath;
}
Then you will probably want an img tag somewhere in your document, instead of the div you are using now:
<img id="changing-image"></img>
Then you can use more javascript to find the image and change its src property:
var image = document.getElementById("changing-image");
image.src = getRandomImage();

how to implement automatic sliding images through array in javascript

I want to implement sliding images as soon as the website loads.
Here's my html code
<html>
<title>Wold of Guitars</title>
<body onload="images()">
</body>
</html>
And here's my javascript
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '../img/n/h1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '../img/n/h2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '../img/n/home.jpg';
imgArray[3] = new Image();
imgArray[3].src = '../img/n/h3.jpg';
imgArray[4] = new Image();
imgArray[4].src = '../img/n/h4.jpg';
x=-1;
function images()
{ x=x+1
if(x>4)
x=1
document.write("<li><img src='" + imgArray[x] + "' width="1350" height="630"/><span>" + imgArray[] + "</span></li>");
var t=setInterval("images()",3000);
}
Help will be appreciated.
Although you mentioned "sliding" your initial code looked liked you wanted to swap the images over time.
I admit you may struggle to find good resources on JavaScript for something so simple, which Is why I can relate to your question.
Ok so here's a quick & dirty but more modern-ish image changing slide requestAnimationFrame:
https://jsfiddle.net/julienetienne/95tqftnk/4/
The same principals apply for making images slide except you are pre-loading all images and shifting the position by the slide show width.
var speed = 3;
// Your image array
var images = [
'http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg',
'http://www.hdwallpapersimages.com/wp-content/uploads/images/Child-Girl-with-Sunflowers-Images.jpg',
'http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg'];
// Get the slideShow tag
var slideShow = document.getElementById('slide-show');
// Create the image tag //You could also just make one in HTML and get the tag
var img = document.createElement('img');
// Append the image to the slideshow container
slideShow.appendChild(img);
// Basic request animation polyfill
var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
return setTimeout(callback, 1000 / 60);
};
// declare var count outside of rAF loop
var count;
function changeImage(timeStamp) {
count = Math.floor(timeStamp / 1000 / speed);
while (count > images.length -1) {
count -= images.length;
}
img.src = images[count];
rAF(changeImage);
}
rAF(changeImage);
img {
width: 600px;
height auto;
}
<div id="slide-show"></div>

A simple way to add smoother transition between background images that change after specified time?

I have my JavaScript set up so that the background image in div#hero alternates between 3 different images every 5000 milliseconds.
Two problems:
How do I add a smooth fade transition as it changes images?
The first 5000 milliseconds before the function begins, no image displays. What is the simplest way to display the first image without waiting the time interval, and then proceed to go by the interval time after the original page load?
var interval_time = 5000;//in milliseconds
setInterval(carousel, interval_time);
function carousel(){
var imgCount = 3;
var dir = 'images/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "1.jpg",
images[2] = "2.jpg",
images[3] = "3.jpg",
document.getElementById("hero").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
}
You have a few options. I would suggest something like this:
var interval_time = 5000;//in milliseconds
function carousel(){
var imgCount = 3;
var dir = 'images/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = ["1.jpg","2.jpg","3.jpg"];
document.getElementById("hero").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
setInterval(carousel(), interval_time);
};
document.addEventListener('DOMContentLoaded', function() {
carousel();
});
Hope that helps!

Download changing background images immediately

I created site with changing background images.
HTML:
<div id="templatemo_header">
</div>
CSS:
#templatemo_header {
background: url(images/templatemo_header.jpg) no-repeat;
}
And JS code which changes the BG image each 3 seconds
function displayImage(image) {
document.getElementById("templatemo_header").style.backgroundImage = image;
}
function displayNextImage() {
x = (x == images.length - 1) ? 0 : x + 1;
displayImage(images[x]);
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
displayImage(images[x]);
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = 'url("images/templatemo_header1.jpg")';
images[1] = 'url("images/templatemo_header2.jpg")';
images[2] = 'url("images/templatemo_header3.jpg")';
images[3] = 'url("images/templatemo_header.jpg")';
The problem is when each of BG images changed only first time, image dissapeares and after some moment new image appears.
I guess, it's because new BG image is downloaded.
Is it some way to force download the images immediately, say in function startTimer?
Thanks in advance.
There are a few ways to pre-load images using javascript here. By pre-loading the images you may have better luck when displaying them. In your case I would use Method 3 if possible, if not Method 2. As described in the article, you would use the window.onload event to kick off the downloading of the images once the page has loaded.
I would just setup your image array as follows:
window.onload = preLoadImages();
function preLoadImages(){
preLoadImage = new Image();
images[0] = "images/templatemo_header1.jpg";
images[1] = "images/templatemo_header2.jpg";
images[2] = "images/templatemo_header3.jpg";
images[3] = "images/templatemo_header.jpg";
for(i=0, i<=images.length, i++){
preLoadImage.src=images[i];
}
}

Javascript load images in canvas with JCanvaScript

I am using JcanvaScript library to work with Html5 canvas and now I want to load some images in my Canvas, but only last image loading is successful, I can't see any other images but the last one and I don't know what is wrong with my code.
here is the code
<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {
border: 1px solid #9C9898;
}
</style>
<script src="jcanvas/jCanvaScript.1.5.15.js"></script>
<script>
var imagesUrl = [];
var imagesObj = [];
var canvasWidth = 800;
var canvasHeight = 600;
var imagesIdPrefix = 'images_';
var canvas = "canvas";
var fps = 60;
imagesUrl.push('images/image1.jpg');
imagesUrl.push('images/image2.jpg');
imagesUrl.push('images/image3.jpg');
imagesUrl.push('images/image4.jpg');
function init(){
for (i = 0; i < imagesUrl.length; i++){
var xImage = new Image();
xImage.src = imagesUrl[i];
xImage.onload = function(){
jc.start(canvas, fps);
jc.image(xImage, i*10, 0, 200, 200)
.id(imagesIdPrefix.toString() + i.toString());
jc.start(canvas, fps);
}
imagesObj.push(xImage);
}
}
</script>
</head>
<body onload="init()">
<canvas id="canvas" width="800px" height="600px"></canvas>
</body>
</html>
The bug has been identified in comment by MrOBrian : when the onload callbacks are called, i has the value it has at the end of the loop. That's the reason why you think that only last image loading is successful.
A standard solution is to embbed the content of the loop in a closure keeping the value of i :
for (i = 0; i < imagesUrl.length; i++){
(function(i){
var xImage = new Image();
xImage.src = imagesUrl[i];
xImage.onload = function(){
jc.start(canvas, fps);
jc.image(xImage, i*10, 0, 200, 200)
.id(imagesIdPrefix.toString() + i.toString());
jc.start(canvas, fps);
}
imagesObj.push(xImage);
})(i);
}
EDIT :
when you want to ensure all the needed images are loaded before running some code, you may use this function :
function onLoadAll(images, callback) {
var n=0;
for (var i=images.length; i-->0;) {
if (images[i].width==0) {
n++;
images[i].onload=function(){
if (--n==0) callback();
};
}
}
if (n==0) callback();
}
The images must have been provided their src first. You call the function like this :
onLoadAll(imagesObj, function(){
// do something with imagesObj
});
You need to make sure the images are loaded before you go and loop through them.
By defining your onload function inside of the for loop, the image may not have loaded by that point, and so the script will skip over it. And when it's done looping, the last image may be the only one that's loaded in time.
I would recommend adding a loader for each of the images outside the for loop, and when all the images are loaded go ahead and loop through the array.
A loader and checker looks something like this:
var loadedImages = [];
var loadedNumber = 3 //the number of images you need loaded
var imageToBeLoaded = new Image();
imageToBeLoaded.onload = function() {
loadedImages.push(true);
checkImages();
}
function checkImages() {
if (loadedImages.length != loadedNumber) {
setTimeout(checkImages(),1000);
} else {
init(); //your draw function
}
}

Categories