HTML5 canvas slide show issue - javascript

I have a slideshow that I am triggering with a call from a link. The slideshow is working well. I am having problems stopping AND clearing the slideshow. I have a temporary link that I am calling the stopShow function that is stopping the show, but is not clearing it so I can then redisplay other items.
// JavaScript Document
var imagePaths = ["_sites/BBB_homepage.png","_sites/CabezonKidsDental_homepage.png","_sites/djer_homepage.png","_sites/enchanted_homepage.png","_sites/JoeSSausage_homepage.png","_sites/MMCS_homepage.png","_sites/mySRB.png","_sites/PHCP_homepage.png","_sites/smilesforkidsnm_homepage.png","_sites/t2consulting_homepage.png","_sites/Upward_homepage.png","_sites/Webb_based_homepage.png"];
var showCanvas = null;
var showCanvasCtx = null;
var img = document.createElement("img");
var currentImage = 0;
var revealTimer;
var stopShow = 0;
var slideTImer;
function slideShow() {
if (!stopShow){
showCanvas = document.getElementById('Canvas1');
showCanvasCtx = showCanvas.getContext('2d');
//clear canvas
showCanvasCtx.clearRect(0,0,showCanvasCtx.canvas.width,showCanvasCtx.canvas.height);
//set image size and call switch function
img.setAttribute('width','500');
img.setAttribute('height','400');
switchImage();
//start the animation
slideTimer = setInterval(switchImage,3000);
}
}
function switchImage() {
//set img element source property to images in slideshow
img.setAttribute('src',imagePaths[currentImage++]);
//if past the last image, loop
if (currentImage >= imagePaths.length)
currentImage = 0;
//fade into image by 10th of full saturation
showCanvasCtx.globalAlpha = 0.1;
revealTimer = setInterval(revealImage,100);
}
function revealImage() {
showCanvasCtx.save();
showCanvasCtx.drawImage(img,100,0,500,400);
showCanvasCtx.globalAlpha += 0.1;
if (showCanvasCtx.globalAlpha >= 1.0) clearInterval(revealTimer);
showCanvasCtx.restore();
}
function stopSlideShow() {
//alert('stop show');
clearInterval(slideTimer);
clearInterval(revealTimer);
stopShow=1;
showCanvas = document.getElementById('Canvas1');
showCanvasCtx = showCanvas.getContext('2d');
//clear canvas
showCanvasCtx.clearRect(0,0,showCanvasCtx.canvas.width,showCanvasCtx.canvas.height);
}

This is wrong!
showCanvasCtx.canvas.width
The object model of the canvas works this way:
Canvas -> Context
the width and height parameters are not in the Context but in the Canvas itself. So, considering you got them this way in your code:
showCanvas = document.getElementById('Canvas1');
showCanvasCtx = showCanvas.getContext('2d');
you should get the dimensions of the canvas like this:
showCanvas.width
showCanvas.height

By removing if (!stopShow){ call, and clearing the canvas in the stopSlideShow function, the function works as desired. It was necessary to set the globalAlpha to 1 in the stopSlideShow function. The ending code looks like this:
// JavaScript Document
var imagePaths = ["_sites/BBB_homepage.png","_sites/CabezonKidsDental_homepage.png","_sites/djer_homepage.png","_sites/enchanted_homepage.png","_sites/JoeSSausage_homepage.png","_sites/MMCS_homepage.png","_sites/mySRB.png","_sites/PHCP_homepage.png","_sites/smilesforkidsnm_homepage.png","_sites/t2consulting_homepage.png","_sites/Upward_homepage.png","_sites/Webb_based_homepage.png"];
var showCanvas = null;
var showCanvasCtx = null;
var img = document.createElement("img");
var currentImage = 0;
var revealTimer;
var stopShow = 0;
var slideTImer;
function slideShow() {
showCanvas = document.getElementById('Canvas1');
showCanvasCtx = showCanvas.getContext('2d');
//clear canvas
showCanvasCtx.clearRect(0,0,showCanvas.width,showCanvas.height);
//set image size and call switch function
img.setAttribute('width','500');
img.setAttribute('height','400');
switchImage();
//start the animation
slideTimer = setInterval(switchImage,3000);
}
function switchImage() {
//set img element source property to images in slideshow
img.setAttribute('src',imagePaths[currentImage++]);
//if past the last image, loop
if (currentImage >= imagePaths.length)
currentImage = 0;
//fade into image by 10th of full saturation
showCanvasCtx.globalAlpha = 0.1;
revealTimer = setInterval(revealImage,100);
}
function revealImage() {
showCanvasCtx.save();
showCanvasCtx.drawImage(img,100,0,500,400);
showCanvasCtx.globalAlpha += 0.1;
if (showCanvasCtx.globalAlpha >= 1.0) clearInterval(revealTimer);
showCanvasCtx.restore();
}
function stopSlideShow() {
//alert('stop show');
clearInterval(slideTimer);
clearInterval(revealTimer);
stopShow=1;
img.setAttribute('src',100);
showCanvas = document.getElementById('Canvas1');
showCanvasCtx = showCanvas.getContext('2d');
showCanvasCtx.globalAlpha=1;
}

Related

Getting the width of an Object and offseting not working

So I'm attempting to set up a rotating banner on my website (viewable at https://www.leapcraft.net) and I have a variable that gets the width of the element and should be offsetting the element not inside of the div by the number of pixels.
I've tried setting the values back to their original offset which fixes it.
var bannerStatus = 1;
var bannerTimer = 4000;
var element = document.getElementById("main-banner");
var positionInfo = element.getBoundingClientRect();
var o = positionInfo.width;
window.onload = function() {
bannerLoop();
}
var startBannerLoop = setInterval(function() {
bannerLoop();
}, bannerTimer);
function bannerLoop() {
if (bannerStatus === 1) {
document.getElementById("imgban2").style.opacity = "0";
setTimeout(function() {
document.getElementById("imgban1").style.right = "0px";
document.getElementById("imgban1").style.zIndex = "1000";
document.getElementById("imgban2").style.right = "-"+ o;
document.getElementById("imgban2").style.zIndex = "1500";
document.getElementById("imgban3").style.right = o;
document.getElementById("imgban3").style.zIndex = "500";
}, 500);
setTimeout(function(){
document.getElementById("imgban2").style.opacity = "1";
}, 1000);
bannerStatus = 2;
}
Expected Results: Rotating banner that is responsive to Width of device that is defined in style.css
Why you can't use css styles to rotate image? Look on my solution, maybe will be useful to you.
function bannerLoop() {
imgBanner[imgNum].style.opacity=1;
imgBanner[imgNum].style.WebkitTransitionDuration='';
imgBanner[imgNum].style.webkitTransform = '';
setTimeout(()=>{
imgBanner[imgNum].style.WebkitTransitionDuration='1s';
imgBanner[imgNum].style.webkitTransform = 'rotate(360deg)';
imgBanner[imgNum].style.opacity=0;
(imgNum<imgBanner.length-1)?imgNum++:imgNum=0
},3000)
}
And here is a working fiddle: https://jsfiddle.net/udtr659y/

Image Sequence to Video using Javascript

I have 7 images and each image has 25 frames. What I need to do is that wander around each image by frames and display it as a video which can be controlled by play, pause and stop buttons.
What I can do is that making a video player that I can easily import a video and play, pause, stop in it. I designed it already but do not have any idea how to make a video from a list of images.
You can view the images at these URLs:
-http://storage.googleapis.com/alyo/assignments/images/0.jpg
- http://storage.googleapis.com/alyo/assignments/images/6.jpg
Any help will be appreciated.
You can achieve it using javscript setTimeout() method and div element like that:
var left = 0;
var top = 0;
var minLeft = -512;
var minBottom = -288;
var xDecrement = 128;
var yDecrement = 72;
var myImage = document.getElementById("myImage");
var imgIndex = 0;
let imageList = ['http://storage.googleapis.com/alyo/assignments/images/0.jpg','http://storage.googleapis.com/alyo/assignments/images/6.jpg'];
var playbackStates = {"INIT":0, "RUNNING": 1 , "PAUSE":2};
var activeState = playbackStates.INIT;
myImage.style.backgroundPositionX = "0px";
myImage.style.backgroundPositionY = "0px";
var timerHandler = null;
var play = function(){
if(timerHandler){
clearTimeout(timerHandler);
if(activeState === playbackStates.PAUSE){
return;
}
}
timerHandler = setTimeout(function(){
let pos =parseFloat(myImage.style.backgroundPositionX.replace("px",""));
myImage.style.backgroundPositionX = ( pos - xDecrement) + "px";
if(pos <= -512){
myImage.style.backgroundPositionX ="0px";
pos =parseFloat(myImage.style.backgroundPositionY.replace("px",""));
myImage.style.backgroundPositionY = ( pos - yDecrement) + "px";
if(pos <= -288){
myImage.style.backgroundPositionY = "0px";
imgIndex ++;
if(imageList.length <= imgIndex) return;
myImage.style.backgroundImage = "url("+imageList[imgIndex]+")";
}
}
play();
}, 160)
};
myImage.style.backgroundImage = "url("+imageList[imgIndex]+")";
play();
activeState = playbackStates.RUNNING;
function pause(){
activeState = playbackStates.PAUSE;
}
function resume(){
activeState = playbackStates.RUNNING;
play();
}
<div style="width:128px;height:72px;" id="myImage"></div>
<input type="button" onclick="pause()" value="Pause"/>
<input type="button" onclick="resume()" value="Resume"/>
You can add all your image url's in "imageList" array, also adjust the speed by modify the timeout interval.

JavaScript load images with specific duration

I have two arrays : The first with images paths and the second is with different duration and I am trying using the following functions to set dynamically the 'setTimeout' of my 'changeImage()' function as follow:
function changeImage(){
var img = document.getElementById("img");
img.src = images[x];
var ztme = tme[x];
x++;
if(x >= images.length){
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()",ztme ); //This is the problem!
}
function fadeImg(el, val, fade){
if(fade === true){
val--;
}else{
val ++;
}
if(val > 0 && val < 100){
el.style.opacity = val / 100;
setTimeout(function(){fadeImg(el, val, fade);}, 10);
}
}
var images = [],
x = 0;
images[0] = "daki/eco_pic.jpg";
images[1] = "daki/art_tnt.gif";
images[2] = "daki/mkv_uk.jpg";
images[3] = "daki/bolo_trt.jpg";
images[4] = "daki/folo_fr.jpg";
var tme = [], //values of 'Time' for a picture to stay displayed
tme[0]= 10000;
tme[1]= 50000;
tme[2]= 2000;
tme[3]= 30000;
tme[4]= 5000;
setTimeout("changeImage()", 15000);
If I give a fixed number for the timeout everything is working like a charm. Therefore to set it dynamically generates just errors.
Any idea to let this changeImage() function get dynamically the time?
Am gratefull to any help.
Thank you in advance.
Your tme array is not properly initialized.you should used semi column after its declaration;
var tme = []; //<=
tme[0]= 10000;
tme[1]= 50000;
tme[2]= 2000;
tme[3]= 30000;
tme[4]= 5000;
setTimeout("changeImage()", 15000);

Stopping and starting a slideshow with onclick event

I want to control this slideshow to start/stop using onclick on #mainImage. At this point, I can get the slides to stop, but I'm stuck on the logic for how to use onclick to start it again. Ideally, I want the slideshow to continue from the array position where it left off as opposed to starting over completely. My instinct tells me this could be solved with some conditional statements, but I just can't get it to work. Thanks for any feedback!
//Grab img
var mainImage = document.getElementById("mainImage");
//Create image array
var imageArray = ["images/drifter.jpg","images/drifter3.jpg","images/drifter4.jpg"];
//Set up array index
var imageIndex = 0;
//Create function to cycle through images
function changeImage() {
mainImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
//Call cycle function
var intervalHandle = setInterval(changeImage,3000);
mainImage.onclick = function () {
clearInterval(intervalHandle);
}
Add a flag to know when it stopped and when should continue
//Grab img
var mainImage = document.getElementById("mainImage");
//Create image array
var imageArray = ["images/drifter.jpg","images/drifter3.jpg","images/drifter4.jpg"];
//Set up array index
var imageIndex = 0;
// here the flag
var stop = false;
//Create function to cycle through images
function changeImage() {
mainImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
//Call cycle function
var intervalHandle = setInterval(changeImage,3000);
mainImage.onclick = function () {
if(!stop){
clearInterval(intervalHandle);
stop = true;
} else {
intervalHandle = setInterval(changeImage,3000);
stop = false;
}
}

Why is it looping through the 'else' in my if/else statement?

If you enable the alert(rand) at the bottom of my if/else statement, you will notice that when ran, it will constantly loop over the else section of my if/else statement. It's probably a simple fix, but I can't seem to figure it out. I had it working in the earlier stages of development but can't seem to figure it out now.
I'll post the code below, but it's probably easier to look at my jsfiddle, here: http://jsfiddle.net/zAPsY/7/ Thanks.
$(document).ready(function(){
//You can edit the following file paths to change images in selection
var img1 = '<img src="images/luke.jpg">';
var img2 = '<img src="images/luke.jpg">';
var img3 = '<img src="images/luke.jpg">';
var img4 = '<img src="images/luke.jpg">';
var img5 = '<img src="images/luke.jpg">';
var img6 = '<img src="images/luke.jpg">';
var all = img1 + img2 + img3 + img4 + img5 + img6;
//Rotation
var speed = 0.00;
var radius = 80;
var count = 0;
$("#run").bind("click",runButtonClick);
function rotate()
{
var centerx = $(document).width()/2;
var centery = $(document).height()/2;
var num_items = $("#container > img").length;
$("#container > img").each(function(){
var angle = count * (Math.PI/180);
var newx = centerx + Math.cos(angle)*radius - $(this).width()/2;
var newy = centery + Math.sin(angle)*radius - $(this).height()/2;
$(this).css("left",newx+"px").css("top",newy+"px");
count += 360/num_items + speed;
});
}
setInterval(rotate,100/1000);
//Append elements to container
$("#appendall").click(function(){$('#container').append(all);});
$('#append').children().eq(2).click(function(){$('#container').append(img1);});
$('#append').children().eq(3).click(function(){$('#container').append(img2);});
$('#append').children().eq(4).click(function(){$('#container').append(img3);});
$('#append').children().eq(5).click(function(){$('#container').append(img4);});
$('#append').children().eq(6).click(function(){$('#container').append(img5);});
$('#append').children().eq(7).click(function(){$('#container').append(img6);});
//Refresh page
$("#reset").click(function(){location.reload();});
//IF speed is greater than 0 - ELSE add animation to div element
function runButtonClick() {
var maxcount = 0.40;
var incdec = 0.01;
setInterval(function(){counter();}, 100);
counter()
speed;
function counter()
{
if (maxcount >= 0.00)
{
maxcount = maxcount - incdec;
speed = speed + incdec;
//alert(speed)
//alert(maxcount)
}
else if (maxcount <= 0.00)
{
speed = 0.00;
//Find amount of div elements and add 1
var brewees = $('#container').children().length +=1;
//get a random number
var rand = (Math.floor(Math.random()*brewees));
var ap = '20px';
var ab = '#ddd';
var ad = 1000;
//match random number corrosponding child in div
$('#container').children().eq(parseFloat(rand))
.animate({padding: ap, background : ab}, {duration:ad});
alert(rand);
}
}
}
});
You let your maxcount drop below zero but still your function is being called every 100ms (due to your setInterval).
So you should clear that interval eventually by doing:
/* first */
var intervalID = setInterval(function(){counter();}, 100);
/* later */
clearInterval(intervalID);
You're calling the function at a rate of 10 times per second (setInterval). Eventually, the maxcount variable will drop below 0, causing the else condition to execute.
You should store the interval call in a variable, and use clearInterval at else, so that the function runs only once after else:
//Store a reference to the interval
var interval = setInterval(function(){counter();}, 100);
...
function counter(){
...
else if(..){
...
clearInterval(interval); //Clear the previously defined interval
}
...
Another note: In the code, speed; has no use. Either prefix it by var (var speed;), or remove it.

Categories

Resources