Traffic light on a timer using Javascript - javascript

I have been asked to create a traffic light that goes through the sequence set using arrays.
I have managed to create a traffic light that works with the user pressing a button every time they would like to change the colour of the traffic light however, I have now been tasked with making it so the user only has to press the button once and then it goes through the sequence automatically using JavaScript.
The images used in the code are located in the same folder as the script.
<img id="Change Lights" src="red.gif" width="36" height="98">
<br>
<button onclick="nxt()" id="button">Change colour</button>
</br>
<script>
var img = new Array("red.png", "amberred.png", "green.png", "amber.png");
var imgElement = document.getElementById("Change Lights");
var lights = 0;
var imgLen = img.length;
function nxt() {
if (lights < imgLen - 1) {
lights++;
} else {
lights = 0;
}
imgElement.src = img[lights];
}
</script>

<img id="Change Lights" src="https://placehold.it/36x98/ff0000" width="36" height="98">
<script>
var img = ["https://placehold.it/36x98/ffbf00","https://placehold.it/36x98/00ff00","https://placehold.it/36x98/ff0000"];
var imgElement = document.getElementById("Change Lights");
var lights = 0;
var imgLen = img.length;
function nxt() {
if (lights < imgLen - 1) {
lights++;
} else {
lights = 0;
}
imgElement.src = img[lights];
}
setInterval(nxt,2000);
</script>

Related

JavaScript while loop through a video while automatically playing and pausing

How can I efficiently write a JavaScript while loop code to automatically play a one hour video while playing for three seconds and pausing for six seconds to allow me time to transcribe? This is what I have tried but I have not succeeded.
<!DOCTYPE html>
<html>
<head>
<title> Video transcription</title>
</head>
<body>
</body>
<video id = 'myVideo' >
<source src = 'testVideo.mp4'>
</video>
<script>
var pauseTime = 6000 // six seconds
var initialTime = 0
var timeUpdate = 3
var timeIncrement = initialTime + timeUpdate
var wasPausedBefore1 = 0;
var wasPausedBefore2 = 0;
var wasPausedBefore3 = 0;
while (video.duration > 0) {
var video = document.getElementById('myVideo');
video.play();
video.ontimeupdate = function() {
let currentTime =video.currentTime;
if (currentTime > initialTime && currentTime < timeIncrement && wasPausedBefore1 == 0) {
video.pause();
wasPausedBefore1 = 1;
setTimeout(function() {
video.play();
}, pauseTime);
} else if(currentTime > initialTime && currentTime < timeIncrement && wasPausedBefore2 == 0){
video.pause();
wasPausedBefore2 = 1;
setTimeout(function() {
video.play();
}, pauseTime);
}
initialTime += timeUpdate
timeIncrement += timeUpdate
}
}
</script>
</body>
</html>
I did the following to create a control logic of your application:
Created a Petri Net diagram of the control logic. I used Notepad to create the diagram as PDF form XObject.
Created an interactive prototype of the control logic as a PDF form application.
Created the control logic of the application based on the prototype. I used the setTimeout API instead of a loop structure.
For me this is an effective way to create the control logic of many applications because creating the interactive prototype based on a Petri Net diagram is a systematic activity.
The interactive prototype plus details on its construction and additional sample source codes are available in a dynamic and interactive PDF at https://www.academia.edu/43005182/How_to_Automatically_Play-and-Pause_a_Video_A_Reply_to_a_Request_at_Stack_Overflow.
The following HTML code is an example of how to use the control logic.
<!DOCTYPE html>
<head>
<title>Play-and-Pause Example</title>
</head>
<body>
<video id = 'video0'>
<source src = '1956Pepto_512kb.mp4'>
</video>
<script>
/* Copyright 2020 John Frederick Chionglo */
var tObject;
var vTime = 64000;
var vID = document.getElementById('video0');
function PlayAndPause(parms) {
this.videoID = parms.videoID;
this.videoTime = parms.videoTime;
this.tObject = undefined;
}
PlayAndPause.objs = [];
PlayAndPause.play = function(id) {
PlayAndPause.objs[id].playSegment(id);
};
PlayAndPause.pause = function(id) {
PlayAndPause.objs[id].pauseSegment(id);
};
with (PlayAndPause) {
prototype.window = this;
prototype.playTime = 3000;
prototype.pauseTime = 6000;
prototype.playSegment = function(id) {
this.videoID.play();
this.videoTime -= this.playTime;
this.tObject = setTimeout("PlayAndPause.pause("+ id + ")", this.playTime);
};
prototype.pauseSegment = function(id) {
if (this.videoTime<0) {}
else {
this.videoID.pause();
this.tObject = setTimeout("PlayAndPause.play(" + id + ")", this.pauseTime);
}
};
}
var ppobj = new PlayAndPause({videoID: vID, videoTime: vTime});
PlayAndPause.objs[0] = ppobj;
ppobj.playSegment(0);
</script>
</body>
</html>

video Javascript, HTML5, efect

I am currently working on the treatment of stereoscopic side by side videos, the user can choose the effect he wants to add on his video (black and white, sepia, anaglyph (which is still not done )) I added buttons for example normal and black and white, when I click on the normal button my video is displayed perfectly well then by clicking on the black and white button I try to have the effect B / W but the result that shows me is N / b..normal .... N / b ... normal ... N / b ... normal, I do not see where the problem is I need help thank you :)
<!DOCTYPE html>
<meta charset=utf-8 />
<script src="video.js" type="text/javascript"></script>
<link href="video-js.css" rel="stylesheet" type="text/css">
<title>Mon projet </title>
<h1> <marquee>Streaming </marquee></h1>
<center>
<h1> Choisir effet </h1>
<span id="cvsModeLbl">Mode:</span>
<input type="button" id="cvsbtnNormal" value="Normal" />
<input type="button" id="cvsbtnBW" value="Black & White" />
<h1> Vidéo Side by side</h1>
<video id=v controls loop width="500" height="400">
<source src=video2.mp4 type=video/mp4>
<source src=video2.webm type=video/webm>
<source src=video2.ogg type=video/ogg>
</video>
<canvas id=c width="500" height= "400"></canvas>
<style> c { background: black; } </style>
<script>
var v = document.getElementById('v');
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
var back = document.createElement('canvas');
var backcontext = back.getContext('2d');
var back1 = document.createElement('canvas');
var backcontext1 = back1.getContext('2d');
v.crossOrigin = 'anonymous';
var cw,ch;
cw = v.width;
ch = v.height;
back.width=cw;
back.hight=ch;
back1.width=cw;
back1.height=ch;
var effectNormal = document.getElementById("cvsbtnNormal");
var effectBw = document.getElementById("cvsbtnBW");
effectNormal.addEventListener("click", myFunction);
effectBw.addEventListener("click", myFunction1);
function myFunction(){
context.clearRect(0,0,500,400);
// First, draw it into the backing canvas
context.drawImage(v,0,0,cw,ch);
setTimeout(function(){ myFunction() }, 0);
}
function myFunction1(){
context.clearRect(0,0,500,400);
context.drawImage(v,0,0,cw,ch);
// Grab the pixel data from the backing canvas
var idata = context.getImageData(0,0,cw,ch);
var data = idata.data;
// Loop through the pixels, turning them grayscale
for(var i = 0; i < data.length; i+=4)
{
var r = data[i],
g = data[i+1],
b = data[i+2],
gray = (r+g+b)/3;
data[i] = gray;
data[i+1] = gray;
data[i+2] = gray;
}
idata.data = data;
// Draw the pixels onto the visible canvas
context.putImageData(idata,0,0);
// Start over!
setTimeout(function(){ myFunction1(); }, 0);
}
</script>
var to1, to2;
function myFunction(){
clearTimeout(to1)
clearTimeout(to2)
context.clearRect(0,0,500,400);
// First, draw it into the backing canvas
context.drawImage(v,0,0,cw,ch);
to1 = setTimeout(function(){ myFunction() }, 10);
}
function myFunction1(){
clearTimeout(to1)
clearTimeout(to2)
context.clearRect(0,0,500,400);
context.drawImage(v,0,0,cw,ch);
// Grab the pixel data from the backing canvas
var idata = context.getImageData(0,0,cw,ch);
var data = idata.data;
// Loop through the pixels, turning them grayscale
for(var i = 0; i < data.length; i+=4)
{
var r = data[i],
g = data[i+1],
b = data[i+2],
gray = (r+g+b)/3;
data[i] = gray;
data[i+1] = gray;
data[i+2] = gray;
}
idata.data = data;
// Draw the pixels onto the visible canvas
context.putImageData(idata,0,0);
// Start over!
to2 = setTimeout(function(){ myFunction1(); }, 10);
}
If you first click your "Normal" button, function() will be executed as fast and frequently as possible due to setTimeout() and has no way of being stopped.
If you then click your "Black & White" button, function1() will also be executed as fast and frequently as possible due to setTimeout() and has no way of being stopped.
Both functions modify the canvas in alternating fashion as they compete for CPU time.
Please consider using only 1 "render loop", and a way to break out of the loop using a stop button.
Instead of using setTimeout, consider using requestAnimationFrame and a check on video time as described here: https://stackoverflow.com/a/17048103/3931225

Trying to change an image using an array in JavaScript

<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
index=(0)
var traffic = ["Red","Rambo","Green","Yellow"]
function changeImage() {
var image = document.getElementById('Light');
if traffic[index] === "Red" {
image.src = "Rambo.jpg";
index= (index+1)
} else if traffic[index] === "Rambo" {
image.src = "Green.jpg";
index= (index+1)
} else if traffic[index] === "Green" {
image.src = "Yellow.jpg";
index= (index+1)
} else {
image.src = "Red.jpg";
index=0
}
}
</script>
</html>
</body>
this is my code I don't understand why when i click the button the image doesn't change the images are all .jpg files are all contained inside the same folders and all are the same size any ideas why is will not change the image i'm currently guessing it's something to do with the === or the fact i'm using words instead of numbers for them
Lots of things going wrong here:
Parenthese around the if statements
Closing body tag after closing html tag
document.getElementById does not get the same id as the img id
So, this will work, but perhaps checking the javascript and HTML syntax first might be a good start:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
var index = 0;
var traffic = ["Red","Rambo","Green","Yellow"];
var image = document.getElementById('myImage');
function changeImage() {
if (traffic[index] === "Red") {
image.src = "Rambo.jpg";
index++;
} else if (traffic[index] === "Rambo") {
image.src = "Green.jpg";
index++;
} else if (traffic[index] === "Green") {
image.src = "Yellow.jpg";
index++;
} else {
image.src = "Red.jpg";
index = 0;
}
}
</script>
</body>
</html>
There are few little mistakes in your code.
The id of your image is myImage, but you wrote var image = document.getElementById('Light'); which result on undefined.
As mentioned by PierreDuc, you missed parenthesis around if conditions.
Take a look at this example : https://jsfiddle.net/1wjn943x/
var images = [
"http://openphoto.net/thumbs2/volumes/mylenebressan/20120720/openphotonet_11.jpg",
"http://openphoto.net/thumbs2/volumes/sarabbit/20120322/openphotonet_DSCF5890.JPG",
"http://openphoto.net/thumbs2/volumes/Sarabbit/20120117/openphotonet_gerberadaisy3.jpg"
];
var index = 0;
var img = document.getElementById("myImage");
document.getElementById("button").addEventListener('click', function() {
// Next image.
index = (index + 1) % images.length;
// Setting `src`attribute of <img>.
img.src = images[index];
});
This is the easiest way to change the image.
Simply set the image source to be the next image in the array. You need to use the mod operator to loop from the end; back to the beginning.
Array - Index Pointer
var imageEl = document.getElementById('Light');
var index = 0;
var images = [
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
];
function changeImage() {
imageEl.src = images[index++ % images.length]; // Set and increment the image index.
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Map - Linked Pointer
var imageEl = document.getElementById('Light');
var currImage = '';
var images = {
red : {
src : "http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
next : 'rambo'
},
rambo : {
src : "http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
next : 'green'
},
green : {
src : "http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
next : 'yellow'
},
yellow : {
src : "http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow",
next : 'red'
}
};
function changeImage() {
(function(img) {
imageEl.src = img.src; // Set the image source to the current image.
currImage = img.next; // Set current image as the next image.
}(images[currImage || 'red']));
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Class - Circular Iterator
var CircularIterator = function(iterable) {
this.iterable = iterable || [];
this.index = 0;
this.get = function(index) {
return this.iterable[index] || this.next();
};
this.size = function() {
return this.iterable.length;
};
this.incr = function() {
return this.index = ((this.index + 1) % this.size());
};
this.next = function() {
return this.get(this.incr());
};
this.first = function() {
return this.get(0);
};
this.last = function() {
return this.get(this.size() - 1);
};
};
var imageEl = document.getElementById('Light');
var iterable = new CircularIterator([
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
]);
function changeImage() {
imageEl.src = iterable.next(); // Set and increment the image index.
}
imageEl.src = iterable.first(); // Set the current image to the first.
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>

Random image appear when website is loaded

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

change background img each time by clicking link

<body>
<script language="JavaScript">
<!--
var backImage = new Array();
backImage[0] = "pics/img02.jpg";
backImage[1] = "pics/img03.jpg";
backImage[2] = "pics/img04.jpg";
backImage[3] = "pics/img05.jpg";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
backImage = backImage++;
}
}
//-->
</script>
Change
</body>
sorry, i don't get how i exactly should properly integrate code here -hopefully it still worked. what i want to do here: change the background (that works) than add plus one to the background counter so that the next time the link is clicked the next background shows (that doesn't work). it should be quite simple but i couldn't figure it out nevertheless...
Use a static counter that counts from 0 to 3.
var cnt = 0;
function changeBGImage(){
if (document.body){
document.body.background = backImage[cnt];
cnt = (cnt+1) % 4; // mod 4
}
}
There are a couple of issues in your code
backImage = backImage++;
Doesn't increment backImage as you expect. The syntax should be simply backImage++;
Also, to set the background image you need document.body.style.background or document.body.style.backgroundImage = url(...)
Edit
Over and above cycling through the backgrounds via the click handler, if you also need to set the initial background, try something like below, with the initial background set in window.onload.
jsFiddle here
var backImage = [];
var whichImage = 0;
backImage[0] = "http://dummyimage.com/100x100/000000/000000.png";
backImage[1] = "http://dummyimage.com/100x100/FF0000/000000.png";
backImage[2] = "http://dummyimage.com/100x100/00FF00/000000.png";
backImage[3] = "http://dummyimage.com/100x100/0000FF/000000.png";
function changeBGImage(reseedWhichImage){
// If caller has specified an exact index, then reseed to this
if (reseedWhichImage != undefined)
{
whichImage = reseedWhichImage;
}
if (document.body){
document.body.style.backgroundImage = "url(" + backImage[whichImage] + ")";
whichImage++;
if (whichImage >= 4){
whichImage = 0;
}
}
}
// During global load, set the initial background
window.onload = changeBGImage(2);
​

Categories

Resources