JavaScript to make a fast-running image slideshow? - javascript

I am making an image slideshow using native JS.
I decided to make it myself because it needs to run at ~100ms intervals, and without any special transition effects (see it here), so I figured it was unnecessary to include a big library like JQuery just for just a simple application.
This is the code I am currently using [edit: original code - now modified]:
// JavaScript Document
function preloadimages(arr){ // the preloadimages() function is adapted from http://www.javascriptkit.com/javatutors/preloadimagesplus.shtml
var newimages = [], loadedimages = 0;
var postaction = function() {};
var arr = (typeof arr != "object") ? [arr] : arr;
function imageloadpost() {
loadedimages++;
if (loadedimages == arr.length) {
postaction(newimages); //call postaction and pass in newimages array as parameter
}
}
for (var i = 0; i < arr.length; i++) {
newimages[i] = new Image();
newimages[i].src = arr[i];
newimages[i].onload = function() {
imageloadpost();
}
newimages[i].onerror = function() {
imageloadpost();
}
}
return { //return blank object with done() method
done: function(f) {
postaction = f || postaction; //remember user defined callback functions to be called when images load
}
}
}
/* USAGE:
preloadimages(['ed.jpg', 'fei.jpg', 'budapest.gif', 'duck.jpg']).done(function(images) {
images.sort(function(a, b) {
return a.width - b.width; //sort images by each image's width property, ascending
});
alert(images[0].src); //alerts the src of the smallest image width wise
});
*/
function animateSlideshow() {
var num = window.imgNum + 1 ;
if (num >= d['imgs'].length) {
num = 0;
}
window.imgNum = num;
imgTag.src = d['imgs'][num];
var t = window.setTimeout(function(){animateSlideshow(imgNum, imgTag, d)}, 100);
}
var d;
var imgTag;
var imgNum = 0;
$.onDomReady (function () { // This is not JQuery, it's a simple cross-browser library which you can read here: http://assets.momo40k.ch/common/js/$.js
// data is an array that should be already defined on the calling page,
// containing all the necessary information to generate all the rotation slideshows on the page
for (i = 0; i < data.length; i++) {
d = data[i];
var div = document.getElementById(d['id']);
imgTag = $.Elements.getElementsByClassName('theImage', div)[0];
// preload the images...
preloadimages(d['imgs']).done(function(images) {
imgTag.src = d['imgs'][0];
animateSlideshow();
});
}
});
<!-- HTML calling JS Scripts -->
... HTML document ...
<script src="http://assets.momo40k.ch/common/js/$-min.js" language="javascript" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var data = [];
// I would have an index for each slideshow on the page
data[0] = [];
data[0]['id'] = 'rotation2';// the ID of the tag the initial image is in
data[0]['imgs'] = ['http://www.momo40k.ch/images/pages/stefan_lehmann/bat/pic1.png',
'http://www.momo40k.ch/images/pages/stefan_lehmann/bat/pic2.png',
'http://www.momo40k.ch/images/pages/stefan_lehmann/bat/pic3.png',
'... all the images ... '];
</script>
<script src="js/rotation.js" language="javascript" type="text/javascript"></script>
</body>
</html>
This is what the tag the initial image is in looks like:
<div id="rotation2" class="rotation blackbg">
<img src="http://www.momo40k.ch/images/pages/stefan_lehmann/bat/pic1.png" width="300" title="" class="theImage" />
</div>
Now for the question:
this script only allows me to have one single 'slideshow' on the page - because in each iteration of the loop it overrides the imgNum variable. Is there an other, better way of doing this slideshow (if possible without JQuery, otherwise OK), even in a completely different way?
Thank you
EDIT: I have remade the script following Jared Farrish's answer and it's now working fine!

There were some issues I saw with your code or approach, so I decided to redo it with the approach I would take. For instance:
I would use document.images to get all images and, for ones that have the rotator-specific className, to identify (domElement.parentNode) and obtain the containing div, which will give me it's id.
I would use the parentNode.id of the class="rotation" images to create an object with sets (by container ids) I can use to store references to the img nodes.
Use closure scope to stay out of the global scope, as well as be able to share variables between the closure-scoped functions.
Use variable functions to setup the handler and callback functions.
Let me know if you have any questions or find something that doesn't work.
<div id="rotator1" class="rotation blackbg">
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/6/6e/Brandenburger_Tor_2004.jpg" />
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/a/ad/Cegonha_alsaciana.jpg" />
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/d/da/CrayonLogs.jpg" />
</div>
<div id="rotator2" class="rotation blackbg">
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/1/17/Bobbahn_ep.jpg" />
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/9/90/DS_Citro%C3%ABn.jpg" />
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/f/f0/DeutzFahr_Ladewagen_K_7.39.jpg" />
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/c/c7/DenglerSW-Peach-faced-Lovebird-20051026-1280x960.jpg" />
<img class="slides" src="http://upload.wikimedia.org/wikipedia/commons/4/4d/FA-18F_Breaking_SoundBarrier.jpg" />
</div>
var slideshows = function(){
var timeouts = {},
imgs;
function preloadImages(list){
var loading = list,
img,
loaded = {},
newimages = [];
var imageloaded = function(){
// this here is one of the new Image()s we created
// earlier; it's not the "real" image on the screen.
// So I put the reference to the actual image it represents
// on the screen in the rel attribute so I can use it's
// reference; I just have to use this.rel to get it.
var parent = this.rel.parentNode;
// Keeping track of the individual sets loaded.
loaded[parent.id]++;
// Here is where this/self gets it's context from, when
// we .call(parent, 0). It's the parentNode to the image
// we've referenced above. This should only run once,
// when the last image has loaded for the set.
if (loaded[parent.id] == loading[parent.id].length) {
animateSlideshow.call(parent, 0);
}
};
var imagenotloaded = function(){
// this.rel is the reference to the actual image we
// have in the DOM, so we'll set the error flag on it.
this.rel['imageerror'] = true;
imageloaded.call(this);
};
for (var load in loading) {
// loaded is equivalent to imgs.sets, so load is the
// id for the container.
loaded[load] = [];
// Now we're going to loop over every image in the
// current set, creating a Javascript image object
// to initiate the download of the file and tell us
// when it's finished. Not the newimages[i].rel = img
// part.
for (var i = 0, l = loading[load].length; i < l; i++) {
img = loading[load][i];
newimages[i] = new Image();
newimages[i].onload = imageloaded;
newimages[i].onerror = imagenotloaded;
newimages[i].rel = img;
newimages[i].src = img.src;
}
}
}
var animateSlideshow = function(current) {
// this could be used instead of self. I was doing
// something else at first, but making this copy
// of the context (this) is not necessary with this
// code. It doesn't hurt either.
var self = this;
// Our current context is the containing div, so
// this.id/self.id will give us the key to the correct
// group in imgs.sets, and the current argument will
// tell us with image in that list we're currently
// working with. First, we hide the last displayed
// image.
imgs.sets[self.id][current].style.display = 'none';
// Increment to get the next image.
current++;
// If we're at the end, let's move back to the
// beginning of the list.
if (current >= imgs.sets[self.id].length) {
current = 0;
}
// This skips images which had an error on load. The
// test for this in the markup above is the third image
// in rotator1, which is not an image url.
if (imgs.sets[self.id][current].imageerror == true) {
// See how I'm passing self using .call()? This sets
// the context for the next animateSlideshow() call,
// which allows this/self to work on the correct div
// container.
animateSlideshow.call(self, current);
return;
}
imgs.sets[self.id][current].style.display = 'inline';
// Everything is organized by the self.id key, event
// saving the references to the timeouts.
timeouts[self.id] = setTimeout(function(){
animateSlideshow.call(self, current);
}, 100);
};
function getImages(){
var list = document.images,
img,
data = {sets: {}, allimages: []},
parent;
// document.images gives me an array of references to all
// img elements on the page. Let's loop through and create
// an array of the relevant img elements, keying/grouping on the
// parent element's id attribute.
for (var i = 0, l = list.length; i < l; i++){
img = list[i];
parent = img.parentNode;
// parent should now be a reference to the containing div
// for the current img element. parent.id should give us
// rotator1 or rotator2 in the demo markup.
if (parent.className.indexOf('rotation') !== -1) {
if (!data.sets[parent.id]) {
data.sets[parent.id] = [];
}
// Let's put the img reference into the appropriate
// imgs.sets. I also put the img.src into an index
// container in data.allimages; this is also a remnant
// of a previous approach I took. It could probably be
// removed unless you need it.
data.sets[parent.id].push(img);
data.allimages.push(img.src);
}
}
return data;
}
function initializeSlideshows(){
imgs = getImages();
preloadImages(imgs.sets);
}
initializeSlideshows();
};
$.onDomReady(slideshows);
http://jsfiddle.net/DLz92/1

Related

Assign array of image elements to DOM ids

I have an array of URIs that represent .png elements, e.g., "./img/diamond-red-solid-1.png".
I want to assign each element of the array "gameDeck[0], gameDeck[1], etc. to div ids in HTML. Do I need to identify the elements as = SRC.IMG?
var gameDeck[];
var gameBoardCards = function () {
for (let cardArr of cardsToLoad)
gameDeck.push("./img/" + cardArr + ".png");
}
gameBoardCards();
document.addEventListener('DOM Content Loaded', function () {
gameDeck[0] = document.getElementById("card1");
gameDeck[1] = document.getElementById("card2");
etc.
});
The way I'm understanding your question is that you would like to target the divs in your HTML with ids of card1, card2, card3... card12 etc.
You would like to insert an img tag into each of these divs with the src being the URIs of the gameDeck array.
The following code achieves this. I've tested it and it works fine. Hope it helps :)
document.addEventListener('DOMContentLoaded', function () {
//iterate through the gameDeck array.
for (let x = 0;x < gameDeck.length;x++){
//create an img tag for each gameDeck element
var imgElement = document.createElement("img");
//set the source of the img tag to be the current gameDeck element (which will be a URI of a png file)
imgElement.src = gameDeck[x];
//target the div with id "card(x + 1)"
var cardID = "card" + (x + 1);
var cardElement = document.getElementById(cardID);
//append the img tag to the card element
cardElement.appendChild(imgElement);
}
//log the HTML to the console to check it
console.log(document.getElementById('body').innerHTML);
});
Here is a way that you can either insert images as background images, or as <img /> elements into the divs you are referring to:
<div id="card0" style="width: 100px; height: 100px;"></div>
<div id="card1" style="width: 100px; height: 100px;"></div>
let loadedImage = [];
function preloadImages(urls, allImagesLoadedCallback) {
let loadedCounter = 0;
let toBeLoadedNumber = urls.length;
urls.forEach(function(url) {
preloadImage(url, function() {
loadedCounter++;
console.log(`Number of loaded images: ${loadedCounter}`);
if (loadedCounter == toBeLoadedNumber) {
allImagesLoadedCallback();
}
});
});
function preloadImage(url, anImageLoadedCallback) {
img = new Image();
img.src = url;
img.onload = anImageLoadedCallback;
loadedImage.push(img);
}
}
function gameBoardCards() {
for (let i = 0; i < loadedImage.length; i++) {
document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`;
// document.getElementById(`card${i}`).appendChild(loadedImage[i]);
}
}
preloadImages([
`https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/Color_icon_green.svg/2000px-Color_icon_green.svg.png`, `https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/225px-Solid_blue.svg.png`
], function() {
console.log(`all images were loaded`);
gameBoardCards();
// continue your code
});
It may seem like a bit much for what you are trying to accomplish, but I threw in a proper image-loading handler there. The preloadImages function will handle the loading of images, that way they are properly preloaded, and can render to the DOM. Often times, we try to use images before they are properly loaded, resulting in them sometimes not being displayed, despite no errors are being thrown.
The rest of the code is straight forward, in the for loop, it loops through the existing divs and you can either use the current active line document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`; to use the loadedImage[i] image src to load that as the divs's background image. Or you can use the commented-out line directly below that document.getElementById(`card${i}`).appendChild(loadedImage[i]); to insert an <img /> element into that div. Just use either one that works for you.
You can see the code in action in this JS Fiddle demo.
Hope this helps :)

Image src relative path to absolute path

I have website and now making a hybrid app for it.
I get all my blog post using Jquery get method.
However the issue is that <img src="/media/image.png"> is sometime relative url and sometime an absolute url.
Everytime an absolute url breaks the image showing 404 error.
How to write Jquery function to find if src is absolute and change it to
https://www.example.com/media/image.png
I will not be able to provide any code samples I have tried since I am not a front end developer and tried whole day solving it.
Note: I need to change images present only in <div id="details"> div.
You should always use same path for all the images, but as of your case you can loop through images and append the domain, as of the use case I have added the domain in variable you can change it as per your requirement.
You can use common function or image onload to rerender but I h
Note: image will rerender once its loaded.
var imageDomain = "https://homepages.cae.wisc.edu/~ece533/";
//javascript solution
// window.onload = function() {
// var images = document.getElementsByTagName('img');
// for (var i = 0; i < images.length; i++) {
// if (images[i].getAttribute('src').indexOf(imageDomain) === -1) {
// images[i].src = imageDomain + images[i].getAttribute('src');
// }
// }
// }
//jquery solution
var b = 'https://www.example.com';
$('img[src^="/media/"]').each(function(e) {
var c = b + $(this).attr('src');
$(this).attr('src', c);
});
//best approach you are using get request
//assuming you are getting this respone from api
var bArray = ["https://www.example.com/media/image.png", "/media/image.png"]
var imgaesCorrected = bArray.map(a => {
if (a.indexOf(b) === -1) {
a = b+a;
}
return a;
});
console.log(imgaesCorrected);
img {
width: 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/image.png">
<img src="https://www.example.com/media/image.png">
document.querySelectorAll('#details img').forEach(img => {
const src = img.getAttribute('src');
// use regex, indexOf, includes or whatever to determine you want to replace the src
if (true) {
img.setAttribute('src', 'https://www.example.com' + src);
}
});
The best would be to do this with the response html from the ajax request before inserting into the main document so as to prevent needless 404 requests made while changing the src
Without seeing how you are making your requests or what you do with the response here's a basic example using $.get()
$.get(url, function(data){
var $data = $(data);
$data.find('img[src^="/media/"]').attr('src', function(_,existing){
return 'https://www.example.com' + existing
});
$('#someContainer').append($data)'
})
You can just get all the images from an object and find/change them if they don't have absolute url.
var images = $('img');
for (var i = 0 ; i < images.length ; i++)
{
var imgSrc = images[i].attributes[0].nodeValue;
if (!imgSrc.match('^http'))
{
imgSrc = images[i].currentSrc;
console.info(imgSrc);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/test.jpg">
<img src="/media/test.jpg">
<img src="https://www.example.com/media/test.jpg">

Why is Javascript function not being called?

First Question on this site so I hope I do this right! I have a javascript function that I want to display an image (image1.jpg) when the page is loaded, and then every 2 seconds change the image by going through the loop. However only the first image is showing so it seems the JS function is not being called. Can anyone tell me if I am doing something wrong here because it looks fine to me so can't understand why it won't work. Thanks
<html>
<head>
<script type="text/javascript">
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var i = 1;
if(i>images.length-1){
this.src=images[0];
i=1;
}else{
this.src=images[i];
i++;
}
setTimeout("displayImages()", 2000);
}
</script>
</head>
<body onload="displayImages();">
<img id="myButton" src="image1.jpg" />
</body>
</html>
You need to move the line
var i = 1;
outside the displayImages -function or it will start from one each time!
EDIT: But using a global variable is not considered good practice, so you could use closures instead. Also as noted in other answers, you are referencing this which does not refer to the image object, so I corrected that as well as simplified the logic a bit:
<script type="text/javascript">
function displayImages( i ){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var img = document.getElementById('myButton');
img.src = images[i];
i = (i+1) % images.length;
setTimeout( function() { displayImages(i); }, 2000 );
}
</script>
<body onload="displayImages(0);">
You need the value of i to be available at each call, it can be kept in a closure using something like:
var displayImages = (function() {
var i = 0;
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
return function() {
document.getElementById('myButton').src = images[i++ % images.length];
setTimeout(displayImages, 2000);
}
}());
Also, since this isn't set by the call, it will default to the global/window object, so you need to get a reference to the image. That too could be held in a closure.
There are a couple of issues here that are stopping this from working.
First the var i = 1; needs to be moved outside the function to make the increment work. Also note that the first item in an array is 0, not 1.
Second you're using this to refer to change the image's src, but this is not a reference to the image. The best thing to do is use here is document.getElementById instead.
var i, button;
i = 0;
button = document.getElementById('myButton');
function displayImages() {
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if (i > images.length - 1){
button.src = images[0];
i = 0;
}
else{
button.src = images[i];
i++;
}
setTimeout(displayImages, 2000);
}
There's still some room for improvement and optimisation, but this should work.
You are reinitializing value of i every time, so change the following:
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(!displayImages.i || displayImages.i >= images.length) displayImages.i = 0;
document.getElementById('myButton').src = images[displayImages.i];
displayImages.i++;
setTimeout(displayImages, 2000);
}
Functions are objects in JS and because of this:
you can pass them by reference and not as a string improving performance and readability
you can add fields and even methods to a function object like I did with displayImages.i
EDIT: I've realized that there was one more issue src was not being set for button.
Now I've fixed this and also made other improvements.
Here is the fiddle http://jsfiddle.net/aD4Kj/3/ Only image URLs changed to actually show something.
<script type="text/javascript">
var i = 1;
function displayImages(){
.......
........
Just make "i" Global. so that whenever displayImages being called it will not redefined to 1.
<html>
<head>
<script type="text/javascript">
var i = 1;
function displayImages() {
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
i++;
if (i > images.length - 1) {
i = 0;
}
$('#myButton').attr('src', images[i]);
setTimeout(displayImages, 2000);
}
</script></head>
<body onload="displayImages();">
<img id="myButton" src="img1.jpg" height="150px" width="150px"/>
</body>
</html>
Make i global.
here your are using displayImages() recursively and variable for index i. e i assign as local variable in function displayImages() , you need to assign it global variable i.e outside of the function also initialize it from i=0 as array index always start from 0,
your code become
var i = 0; // assign i global
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(i>images.length-1){
document.getElementById('myButton').src=images[0]; //get img by id
i=0; // to get first image
}
else{
document.getElementById('myButton').src=images[i]; //get img by id
i++;
}
setTimeout("displayImages()", 2000);
}

Errors writing image gallery

I'm trying to write a simply image gallery element for a website and I'm having trouble with the code for silly reasons. I've never gotton on with JavaScript and have always found it a headache. I've tried various other image galleries but can't for the life of me get them to actually work correctly either
My current HTML code is like this:
<!DOCTYPE html>
<html>
<head>
<title> Test of slider </title>
<script type="text/javascript" src="slider.js"></script>
</head>
<body>
<div class="slider" id="main">
<img src="#" class="mainImage" />
<div class="sliderImages" style="display: none;">
<img src="companion.jpg"/>
<img src="cookie.jpg" />
<img src="orange.jpg" />
<img src="orangeWhole.jpg" />
</div>
<div class="sliderButtons">
Previous
Next
</div>
</div>
</body>
</html>
with the javascript like this:
this.Slider = new function(){
// Stores the indices for each slider on the page, referenced by their ID's
var indices = {};
var limits = {};
var images = {};
// Call this function after a major DOM change/change of page
this.SetUp = function(){
// obtain the sliders on the page
// TODO restrict to those within body
var sliders = document.getElementsByClassName('slider');
// assign the indices for each slider to 0
for(var i = 0; i < sliders.length; i++){
indices[sliders[i].id] = 0;
var sliderImages = document.getElementsByClassName('sliderImages');
var imagesTemp = sliderImages[0].getElementsByTagName('img');
images[sliders[i].id] = imagesTemp;
limits[sliders[i].id] = imagesTemp.length;
}
}
// advances a certain slider by the given amount (usually 1 or -1)
this.Slide = function(id, additive){
if(indices && id){
indices[id] = indices[id] + additive;
// Check limits
if(indices[id] < 0){
indices[id] = limits[id] - 1;
}
if(indices[id] >= limits[id]){
indices[id] = 0;
}
// alter img to be the new index
document.getElementById(id).getElementsByClassName('mainImage')[0].src = images[id][indices[id]].src;
}
}
}
for(var slider in sliders)
{
// here slider is the index of the array. to get the object use sliders[slider]
}
then you can use 'getElementsByClassName' function
edit
U have included the slider.js on the top of the html. So first it loads the the js and tries to access the elements which are not yet created..Move the tag to the bottom of the page.
sliderImages is an array of divs with classname sliderImages. there is only one that satisfies.
var sliderImages // is a array with 1 item.
// to get the images use sliderImages[0].getElementsByTagName('img');
change
this.Slide = new function(id, additive){
to
this.Slide = function(id, additive){ // otherwise it will be called when the page is loaded with undefined values.
onclick of the link call with quotes
Slider.Slide('main', 1)
You are using a methode I do not know (or you forgot the "s")
var sliderImages = slider.getElementByClassName('sliderImages');
I would use something like the code below. It is important sliderImages will be an array of anything that is of the class "silderImages"
var sliderImages =slider.getElementsByClassName("sliderImages")

Using JQuery to create animation frames from PSD layers

I have a PSD file with a bunch of layers that are frames for an animation. How can I create an animation from this using JQuery/JavaScript?
Will I have to save each layer as a separate image, is there a way to have the one image with multiple layers animated? To clarify, I don't want the actual image to move, I just want different layers to be displayed as if they were frames of an animation. What's the standard way this is done with JavaScript?
Thanks!
Here is a fiddle that demonstrates the javascript timer + individual images approach.
Fiddle: http://jsfiddle.net/ZVFu8/2/
The basic idea is to create an array with the names of your images.
var img_name_arr = [];
var img_name_root = "anim-";
var img_name_ext = ".gif";
var num_images = 12;
// init arr of img names assuming frames are named [root]+i+[extension]
for (i = 0; i<=num_images; i++) {
img_name_arr.push(img_name_root + i + img_name_ext);
}
For the animation, use setInterval(). In javascript, an interval executes periodically. You specify the code to execute and the interval at which the code should be run (in milliseconds).
Every time your interval is called, you can display a new image by setting the "src" attribute of the image tag to the next index in the image_name array.
// Create an interval, and save a handle to the interval so it can be stopped later
anim_interval = setInterval(function() {
$("#player").attr("src", s + img_name_arr[(anim_frame++ % num_images)+1] );
}, frame_interval);
Depending on how long your animation is and how large each image file is, it might be necessary to optimize this by pre-loading these images. Before the animation starts, you could create an img tag for each image and hide it. Then, instead of altering the "src" attribute to change the image, you would actually hide the current image and un-hide the next image in the previous image's place.
Here is the full code if you wish to run this locally:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a id="anim_control" href="">Start</a>
<img id="player" src="" />
<script>
var s = "http://" + atob("YmVucmlkb3V0LmNvbQ==") + "/";
var img_name_arr = [];
var img_name_root = "anim-";
var img_name_ext = ".gif";
var num_images = 12;
var framerate = 1; // Desired frames per second
var frame_interval = 1000/framerate;
$(function(){
// Document is ready
// init arr of img names
for (i = 0; i <= num_images; i++) {
img_name_arr.push(img_name_root + i + img_name_ext);
}
var anim_interval = null;
var playing = false;
var anim_frame = 0;
// Define an interval that will execute every [frame_interval] milliseconds
$("#anim_control").on("click", function(e) {
e.preventDefault();
if (playing == true) {
playing = false;
$(this).html("Start");
clearInterval(anim_interval);
} else {
playing = true;
$(this).html("Stop");
anim_interval = setInterval(function() {
//console.log(s + img_name_arr[(anim_frame++ % num_images)+1]);
$("#player").attr("src", s + img_name_arr[(anim_frame++ % num_images)+1] );
}, frame_interval);
}
});
});
</script>
<style>
#player {
width: 320px;
height: 240px;
border: 1px solid #000;
}
</style>

Categories