Changing 5 images in 5 seconds each using JavaScript - javascript

I'm new to JavaScript, and I don't get how am I supposed to change among 5 different gif images. The assignment is the following:
Your Projects folder for Chapter 11 contains five advertising images for a concert series, concert1.gif through concert5.gif. Create a script that cycles through the images and displays each one for five seconds. Save the document as ConcertAds.html.
Here's the code I have so far:
<!DOCTYPE HTML>
<html>
<head>
<title>Concert Ads</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/* <![CDATA[ */
var concertads = new Array(5);
concertads[0] = new Image();
concertads[1] = new Image();
concertads[2] = new Image();
concertads[3] = new Image();
concertads[4] = new Image();
concertads[0].src = "concert1.gif";
concertads[1].src = "concert2.gif";
concertads[2].src = "concert3.gif";
concertads[3].src = "concert4.gif";
concertads[4].src = "concert5.gif";
var completeAds;
var currImgIndex = 0;
var maxImgIndex = concertads.length-1;
function concertAd() {
if (completeAds) {
completeAds.src = concertads[0].src;
++currImgIndex;
if (currImgIndex > maxImgIndex) {
currImgIndex = 0;
}
}
}
function initImgCycle(adsID) {
completeAds = document.getElementByID(adsID)
if (completeAds) {
setInterval("cycle()", 5000);
}
}
/* ]]> */
</script>
</head>
<body onload="initImgCycle('adBanner');">
<img src="concert1.gif" id="adBanner" alt="Concert Ads" />
</body>
</html>
I'd appreciate any help, I'm really confused. Thank you for your time!

imgCounter=0;
function cycle(){
if(imgCounter<5){
imgCounter++;
document.getElementById("imgX").src="concert" + imgCounter + ".gif";
setTimeout("cycle();", 5000);
}
}
cycle();
be sure to have a
<img id="imgX" src="" alt="img"/>
or something similar in the html

It's not clear whether you want them to each be shown simultaneously for 5 seconds, or for them to be show one after the other for 5 seconds. I went with the first one.
(function() {
var images = [
new Image(), new Image(), new Image(), new Image(), new Image()
];
images[0].src = 'http://bit.ly/sbK2Ub';
images[1].src = 'http://bit.ly/lMMo0n';
images[2].src = 'http://bit.ly/LFtGyc';
images[3].src = 'http://bit.ly/MY3skL';
images[4].src = 'http://bit.ly/M8iQk3';
function show( elem ) {
document.body.appendChild( elem );
}
function remove( elem ) {
document.body.removeChild( elem );
}
window.onload = function() {
images.forEach(function(a, b) {
show( images[b] );
});
window.setTimeout(function() {
images.forEach(function(a, b) {
remove( images[b] );
});
}, 5000);
};
})();
Here is a demo using different images (Click 'Render' to run the code): http://jsbin.com/akoqek/2/edit

So it would be something like below:
`<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
</style>
<title>Goselin Greeting cards</title>
<script type="text/javascript">
/* <![CDATA[ */
imgCounter=0;
function cycle(){
if(imgCounter<5){
imgCounter++;
document.getElementById("imgX").src="concert" + imgCounter + ".gif";
setTimeout("cycle();", 5000);
}
}
/* ]]> */
</script>
</head>
<body onload="initImgCycle('adBanner');">
<h1>Consert Series</h1>
<img id="imgX" src="" alt="img"/>
</body>
</html>
I am trying to figure out the same thing.

Related

Displaying one image in multiple locations

Disclaimer upfront: I'm still very new to JavaScript. (And to programming in general, for that matter.)
So, I'm trying to create an interface that would display an image in multiple aspect ratios, when cropped by object-fit: cover. I'd like to see several aspect ratios side-by-side and be able to test different images as well.
I'm using JavaScript's File API to avoid uploading/downloading. It's also worth noting that I'm doing everything on Google Apps Script so it can be an easily accessible web app.
Right now, I have the <img> in a <div> so I can use replaceChild. That's the only way I've been able to get it to work. You can see it here on CodePen. This is the function I've been using:
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
var placehold = document.getElementById('userImg');
document.getElementById('userImageDiv').replaceChild(img, placeHold);
}
img.id = "userImg";
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
What I've tried:
I tried getting the img.onload function to append img twice:
var placeholdTwo = document.getElementById('imgTwo');
document.getElementById('imageTwoDiv').replaceChild(img, placeholdTwo);
But it only displayed in imgTwo - I'm guessing because the function only creates one FileReader.
I also tried reading the image in one location, then copying it's src to additional locations, but no luck there:
function repeatImg(){
var repeatImage = document.getElementById('userImg').src;
document.getElementById('imageOne').src = repeatImage;
document.getElementById('imageTwo').src = repeatImage;
}
Then, I tried making multiples of the whole handleImage function and calling them all with an event listener, but that didn't work either.
Is there any way to accomplish this?
Simply wrap the original file object, which is a blob, and set that as source. This way you avoid adding up memory usage and base64 encoding/decoding overheads as with a Data-URL - there's no need to create an intermediate image element either - just update the src on the existing ones:
document.querySelector("input").onchange = handleImage;
function handleImage() {
var url = URL.createObjectURL(this.files[0]);
document.getElementById('userImg').src =
document.getElementById('imageOne').src =
document.getElementById('imageTwo').src = url;
}
<label>Select an image: <input type=file></label>
<img id=userImg>
<img id=imageOne>
<img id=imageTwo>
Looking at the linked pen, repeatImg does not get called by the userImgDiv change event listener.
Calling repeatImg() at the end of img.onload works for me.
img.onload = function(){
var placeHold = document.getElementById('userImg');
document.getElementById('userImageDiv').replaceChild(img, placeHold);
repeatImg();
}
CodePen.
I think perhaps I'm missing something, but why not just set the image sources in your img.onload method?
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
var placehold = document.getElementById('userImg');
document.getElementById('userImageDiv').replaceChild(img, placeHold);
document.getElementById('imageOne').src = img.src;
document.getElementById('imageTwo').src = img.src;
}
img.id = "userImg";
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
You're only using one Image. I would do something like this instead:
/* external.js */
//<![CDATA[
var doc, bod, M, I, Q, S, old = onload; // for use on other loads
onload = function(){
if(old)old(); // change old var name if using technique on other pages
doc = document; bod = doc.body;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
Q = function(selector, withinElement){
var w = withinElement || doc;
return w.querySelectorAll(selector);
}
S = function(selector, withinElement){
var w = withinElement || doc;
return w.querySelector(selector);
}
I('form').onsubmit = function(){
return false;
}
// you can put the below code on another page onload if you want
var up = I('upload'), out = I('out'), reader = new FileReader;
up.onchange = function(){
reader.onload = function(){
var img0 = M('img'), img1 = M('img');
img0.src = img1.src = this.result; out.innerHTML = '';
out.appendChild(img0); out.appendChild(img1);
}
reader.readAsDataURL(this.files[0]);
}
}
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#ccc; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='form' name='form'>
<input id='upload' name='upload' type='file' />
</form>
<div id='out'></div>
</div>
</body>
</html>

I am getting an error from the javascript code: var context = document.getElementById("gameCanvas").getContext("2d");

I am working on developing a game. However, I cannot seem to get the context of the canvas as I have before. My HTML file contains the code:
<html>
<head>
<meta charset="utf-8">
<title>Nostalgia</title>
<link rel="stylesheet" href="gameStyles.css"></link>
</head>
<body>
<canavs id="gameCanvas"></canvas>
</body>
<script src="gameScript.js"></script>
</html>
The javascript file is:
context = document.getElementById("gameCanvas").getContext("2d");
const level = [0,0,0,0,0];
var xToDraw = 0;
var yToDraw = 0;
var img0 = new Image();
img0.src = "./images/tiles/grass.png";
var img1 = new Image();
img1.src = "./images/tiles/dirt.png";
var img2 = new Image();
img2.src = "./images/tiles/sand.png";
function drawLevel(){
// solution
level.map((item1) => {
yToDraw-=16
item1.map((item2) => {
if(item2==0){
context.drawImage(img0, xToDraw, yToDraw);
}
xToDraw+=16;
});
});
}
drawLevel();
Note: This is being run using electron, the page is loading to the window.
The error that was being thrown was: TypeError: document.getElementById(...).getContext is not a function
I would appreciate any help in resolving this error.
This is because you have misspelt your canvas tag:
<canavs id="gameCanvas"></canvas>
Should be:
<canvas id="gameCanvas"></canvas>

Image SlideShow using javaScript and HTML5

I am writing code for image slide Show using Java Script and HTML 5. I am using SetInterval() method to call ImageSlider Function repeatedly. Problem is Imageslider function is called only once.
Here is my code
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Booking</title>
</head>
<style>
iframe
{
display:block;
float:middle;
margin: 0 auto;
text-align: center
}
</style>
<body onload="init()">
<script>
function init()
{
setInterval(imageSlider(),5000);
}
function staticVar()
{
if (staticVar.counter == undefined)
{
staticVar.counter = 1
}
else
{
staticVar.counter++
}
return staticVar.counter;
}
function imageSlider()
{
alert("sl");
var j= staticVar();
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '91.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'myBro.jpg';
imgArray[2] = new Image();
imgArray[2].src = 'me.jpg';
document.getElementById("imageSlide").src = imgArray[j].src;
}
</script>
<iframe height="580" width="25%" src="91.jpg" id="imageSlide"> </iframe>
</body >
</html>
You need to use
setInterval(imageSlider,5000);
instead of
setInterval(imageSlider(),5000);
Documentation on setInterval().

Adding a simple image in easeljs

This is my htmlcode:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
<script src="Doge.js"></script>
</head>
<body bgcolor="#C7C7C7" onload="Start();">
<canvas id="DogeCanvas" width="480" height="320"></canvas>
</body>
</html>
And this is my Doge.js code:
function Start() {
var stage = new createjs.Stage("DogeCanvas");
var doge = new Image();
doge.src = "images/doge.jpg"
var bitmap = new createjs.Bitmap(doge);
stage.addChild(bitmap);
stage.update();
}
Why it doesn't show anything on the screen?
What is wrong?
The image is not loaded when the stage is updated. I posted an answer here:
ยป easeljs not showing bitmap
You can add a Ticker to the stage to constantly update it (which most applications do, since there is other things changing over time)
Listen for the onload of the image, and update the stage again
Preload the image with something like PreloadJS before you draw it to the stage.
As stated above you cannot draw your image until you have loaded it. Try this:
<!DOCTYPE HTML>
<html>
<title>Easel Test</title>
<head>
<script src="https://code.createjs.com/easeljs-0.8.0.min.js"></script>
<script>
var stage;
function init() {
stage = new createjs.Stage("myCanvas");
var image = new Image();
image.src = "path/image";
image.onload = handleImageLoad;
}
function handleImageLoad(event) {
var image = event.target;
var bitmap = new createjs.Bitmap(image);
stage.addChild(bitmap);
stage.update();
}
</script>
</head>
<body onload="init();">
<canvas id="myCanvas" width="960" height="580"></canvas>
</body>
</html>

2 or more async requests in javascript to load image or do anything else

Single request and response model at one time do not utilizes full network/internet bandwidth, thus resulting in low performance. (benchmark is of half speed utilization)
how to make this code use 2 or 3 or more async requests instead of one.(ajax)
or do i need multi threading? and is it possible in javascript?
(this is for making a video out of an ip )
every time the image changes on request. and yes i need to be async with multiple fetch requests (not single as i explained above) or you recomend threads?
<html>
<head> <script language="JavaScript">
// Global vars
img = 'http://pastebin.com/i/t.gif';
timeout = 1000;
next = 0;
function onLoad( ) {
setTimeout( 'reloadImage( )', timeout );
}
// Reloader
function reloadImage( ) {
next = ( new Date( ) ).getTime( ) + timeout;
document.images.dv.src = img + "?" + next;
}
</script>
</head>
<body>
<img src="img" name="dv" onLoad="onLoad( )">
</body>
</html>
and
<html>
<head>
</head>
<body>
<div id="container"></div>
<script language="JavaScript">
var canLoad = true;
var container = document.getElementById("container");
var image = document.createElement("img");
image.onload = function() {
canLoad = true;
console.log("Image reloaded.");
}
var imageUrl = "http://url/snapshot.jpg";
var fps = 2;
container.appendChild(image);
function loadImage() {
if (canLoad) {
canLoad = false;
var str = new Date().getTime();
image.setAttribute("src", imageUrl + "?" + str);
console.log("Reloaded now.");
} else {
console.log("Can't reload now.");
}
}
setInterval(loadImage, fps); // 30 fps
</script>
</body>
</html>
Not actually tested, and I think it'll very likely to cause a "stack overflow" eventually (if you directly implement it), but you may still give it a look:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(){
var img="/*url*/";
var interval=50;
var pointer=0;
function showImg(image,idx)
{
if(idx<=pointer) return;
document.body.replaceChild(image,document.getElementsByTagName("img")[0]);
pointer=idx;
preload();
}
function preload()
{
var cache=null,idx=0;;
for(var i=0;i<5;i++)
{
idx=Date.now()+interval*(i+1);
cache=new Image();
cache.onload=(function(ele,idx){return function(){showImg(ele,idx);};})(cache,idx);
cache.src=img+"?"+idx;
}
}
window.onload=function(){
document.getElementsByTagName("img")[0].onload=preload;
document.getElementsByTagName("img")[0].src="/*initial url*/";
};
})();
</script>
</head>
<body>
<img />
</body>
</html>
What it does:
When the initial image loads, preload() is called;
When preload() is called, it creates 5 image cache, and each attach its onload event to showImg();
When showImg() is called, it checks whether the current index is behind current pointer, and if it does, replace the current image with this new one, and call preload();
Back to 2.
If you really going to implement this, increase interval and decrease i<5. Also, a caching/queuing mechanic to check how many images in cache/queue before loading the next queue would be nice.
Also, notice that I didn't use getElementById to get the image, because there will be no stable ID.

Categories

Resources