randomise array html5 java script - javascript

<!-- with thanks to http://stackoverflow.com/questions/25407926/spawn-random-images-
in-canvas-in-javascript-->
<!--http://www.freesfx.co.uk/download/?type=mp3&id=11028
--audio loader--
http://stackoverflow.com/questions/18826147/javascript-audio-play-on-
click-->
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Street</title>
<script type="text/javascript">
var can, ctx;
var sprite = new Array();
var counter = 0;
var rot = 0;
var centerX = -320;
var centerY = -170;
var sprite = new Array(id); // Array to hold the filenames
function init() {
can = document.getElementById("can");
ctx = can.getContext("2d");
// get images into array
sprite[0] = document.getElementById("b1");
sprite[1] = document.getElementById("b2");
sprite[2] = document.getElementById("b3");
sprite[3] = document.getElementById("b4");
// draw lights out
draw();
// wait 3 sec, then begin animation
var t = setTimeout(light, 30);
}
function light() {
var wait = 600;
counter++;
if (counter == 4) {
counter = 0;
wait += (Math.random() * 1500);
rot += .01;
}
draw();
setTimeout(light, wait);
}
function draw() {
ctx.clearRect(0, 0, can.width, can.height);
ctx.save();
ctx.translate(can.width / 2, can.height / 2);
ctx.drawImage(sprite[counter], centerX, centerY);
ctx.restore();
}
function choseRandom(range) {
if (Math.random)
return Math.round(Math.random() * (range-1));
else {
var now = new Date();
return (now.getTime() / 1000) % range;
}
}
var choice = choseRandom(id);
</script>
</head>
<body onload="init()">
<audio id="Mp3Me" autoplay autobuffer controls>
<source src="au1.mp3">
<source src="au1.ogg">
</audio>
<img id="b1" style="display:none" src="1.png" >
<img id="b2" style="display:none" src="2.png" >
<img id="b3" style="display:none" src="3.png" >
<img id="b4" style="display:none" src="4.png" >
<canvas class="canvas" id="can" width="640" height="350" style=" border:1px solid #6F2E0D; ">
</canvas>
<script>
function play(){
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="door.mp3" ></audio>
<div id="container"></div>
<script language="JavaScript">
document.writeln('<td' + '><img src="'
+ ranimage[choice] + '" height="180" width="160" border="0" ><' +
'/td>');
</script>
<div id='container'>
<img id = "image2" src='door.png' />
</body>
</html>
The above code works with thanks to stack overflow.
Basically at the moment this code displays images in sequence non randomly, it uses the array to fetch them, and show them. The code then regulates the speed of the image display. There is also a sound player, and a button with a sound.
I managed after some considerable searching to animate a simple sequence of png files. However I have been trying to ad start stop button and a math random function (preferably the music on-click would start everything going).
I want to add a random function to the array,so that it displays images randomly. however the best I could do was, not to brake the code, or to get is to speed up the animation. Can some one please modify my code to add these functions or please point me to some place that would help.
The randomized array would be really useful.

Demo: http://jsfiddle.net/techsin/dtz0yj4y/
Code
function shuffle (arr) {
arr.forEach(function(e,i){
var rand = ~~(Math.random()*(arr.length-1));
arr[i] = arr[rand];
arr[rand] = e;
});
}
var myArr = [1,2,3,4,5];
shuffle(myArr); //myArr is now shuffled!
Example...

(there was a mistake, updated)
For example,
var array = [1,2,3,4,5]
for(i=0; i<array.length;i++){
var dist = Math.floor( Math.random() * array.length )
var swp = array[i]
array[i] = array[dist]
array[dist] = swp
}
console.log(array) //=> shuffled

Related

downloading multiple html5 generated images as a zip file

i am building a video hosting site. my video player generates video player screenshots by the onclick() function. i am also not sure if these images are deleted or stored after generating.
i have tried surfing around here trying to find a definitive assistance as i lack in javascript knowledge and it's so frustrating. please help me. ask me if you need any more info. :)
here is my html:
<body>
<div id="videoPanel">
<div id="instructions">
<video id="my_video_1" class="video-js vjs-default-skin" width="720px" height="400px" controls preload="none" poster='' autoplay data-setup='{ "aspectRatio":"640:500", "playbackRates": [1, 1.5, 2] }'>
<source src="/Custom-Video-Player/Masamune kun no Revenge - 07.mp4" type='video/mp4' />
</video>
</div>
<button id="clicker" onclick="shoot()">Capture</button><br />
<button id="download" onclick=""> download</button> <br/>
<div id="output" style="display: inline-block; top: 4px; position: relative; border: dotted 1px #ccc; padding: 2px;"></div>
</div>
</body>
this is the javascript for the screenshot generation:
var videoId = 'my_video_1';
var scaleFactor = 0.25;
var snapshots = [];
var w = 720 * scaleFactor;
var h = 400 * scaleFactor;
function capture(video, scaleFactor) {
if (scaleFactor == null) {
scaleFactor = 1;
}
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
return canvas;
}
function shoot() {
var video = document.getElementById(videoId);
var output = document.getElementById('output');
var canvas = capture(video, scaleFactor);
canvas.onclick = function () {
window.open(this.toDataURL());
};
snapshots.unshift(canvas);
output.innerHTML = '';
for (var i = 0; i < 4; i++) {
output.appendChild(snapshots[i]);
}
}
theres also a download button that i want to be able to function as such:
it will number all images in accordance to their generation in regard to the 'capture' button, put them all in a zip file and download when download is pressed.

delayedalert. window.onload calling placement

I am currently trying to time alerts to appear 3 seconds after the viewer grants permission of the webcam. The alerts are supposed to also have audio with them, as they're supposed to be triggered at the same time.
The webcam has a face tracking feature with it, so there is a lot of extra code.
Previously, I asked this question, and it was answered here; why are these alerts not appearing?.
Though I had to move some files around in its folder, to collect particular audio files. Which was stupid of me, because now this isn't producing the same outcome as my previous question had answered.
As the previous answer was to move attach the delayedAlert() to the window.onload, now is making the webcam video not appear.
Any suggests to fix this? I don't know javascript, so please visuals help a lot more than statements.
This is the current code I am working with:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>eve_</title>
<link rel="stylesheet" href="assets/demo.css">
<link rel="icon" rel="preload" href="../images/evecircle.png" />
<script src="../build/tracking-min.js"></script>
<script src="../build/data/face-min.js"></script>
<script src="../node_modules/dat.gui/build/dat.gui.min.js"></script>
<script src="https://code.responsivevoice.org/responsivevoice.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
video, canvas {
margin-left: 70px;
margin-top: 50px;
position: absolute;
}
</style>
<script>
var timeoutID;
function delayedAlert() {
timeoutID = window.setTimeout(slowAlert, 3000);
}
function slowAlert() {
var audio= document.getElementsByTagName('audio')[0];
const audio2 = document.getElementsByTagName('audio')[1];
var audio3 = document.getElementsByTagName('audio')[2];
var audio4 = document.getElementsByTagName('audio')[3];
audio.play();
var myvar1;alert('Oh, there is more of you.');
audio2.play();
var myvar1;alert('Why are there multiple yous?');
audio3.play();
const name = prompt('What is your name?')
const sentence = 'Hello,' + name +'.I am Eve. ....'+name+name+name+'.'+name+'is human...Ive never seen a. human....What does' +name +' look like?';
responsiveVoice.speak(sentence, "US English Female", {
rate: 0.7}
</script>
<script>
window.onload = function() {
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var tracker = new tracking.ObjectTracker('face');
tracker.setInitialScale(4);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.1);
tracking.track('#video', tracker, { camera: true });
tracker.on('track', function(event) {
context.clearRect(0, 0, canvas.width, canvas.height);
event.data.forEach(function(rect) {
context.strokeStyle = '#a64ceb';
context.strokeRect(rect.x, rect.y, rect.width, rect.height);
context.font = '11px Helvetica';
context.fillStyle = "#fff";
context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
});
});
var gui = new dat.GUI();
gui.add(tracker, 'edgesDensity', 0.1, 0.5).step(0.01);
gui.add(tracker, 'initialScale', 1.0, 10.0).step(0.1);
gui.add(tracker, 'stepSize', 1, 5).step(0.1);
};
</script>
</head>
<body>
<div class="demo-container">
<video id="video" width="920" height="540" preload autoplay loop muted></video>
<canvas id="canvas" width="920" height="540"></canvas>
</div>
</div>
<audio>
<source src="../audio/multiple_yous.wav" type="audio/wav" preload=true>
</audio>
<audio>
<source src="../audio/is_something_here.wav" type="audio/wav" preload=true>
</audio>
<audio>
<source src="../audio/oh_something_is_here.wav" type="audio/wav" preload=true>
</audio>
</body>
</html>

drawing more on the canvas without having to create more script tags

I've been attempting to create a ecology simulation and so far its been going good. The code below does work I'm just wondering if theres an easier way to draw more items on the canvas with code instead of manually doing it. The way I'm doing it makes me consider the lag because I will be adding a lot to the code (e.g. move, detected, reproduce, chase, run, etc). Thank you for seeing this
//This tag will regulate the spawning of new sheep/wolves
var totalWolves = 0;
var totalSheep = 0;
var canavs = document.getElementById("canvas");
var body = document.getElementById("body");
//styler
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
function spawnWolves(){
totalWolves++;
var name = "wolf" + totalWolves;
var scrpt = document.createElement("SCRIPT");
document.body.appendChild(scrpt);
scrpt.setAttribute("id", name);
var script = document.getElementById(name);
script.innerHTML = "var rand3 = Math.floor(Math.random() * 100) + 1; var rand4 = Math.floor(Math.random() * 100) + 1; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = 'red'; context.fillRect(rand3, rand4, 10, 10); context.fill();";
}
spawnWolves();
spawnWolves();
spawnWolves();
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
<script>
</script>
</body>
</html>
Your solution seems very complicated ...
Please, take a look at the following code.
<!DOCTYPE html>
<html>
<title>AI spawn test</title>
<canvas id="canvas" width="110" height="110"></canvas>
<script>
var ctx = canvas.getContext("2d");
var drawRect=function(rects){
for (var i=1; i<=rects; i++){
var rand3=Math.floor(Math.random() * 100) + 1;
var rand4=Math.floor(Math.random() * 100) + 1;
ctx.fillStyle='red';
ctx.fillRect(rand3, rand4, 10, 10)
}
}
drawRect(20);
</script>
This type of 'replication' is done by using loop. There are several loop types, but their explanation is too broad. You can browse the net.
I gave you 2 examples below - with for loop and with while loop.
//This tag will regulate the spawning of new sheep/wolves
var totalWolves = 0;
var totalSheep = 0;
var canavs = document.getElementById("canvas");
var body = document.getElementById("body");
//styler
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
function spawnWolves(){
totalWolves++;
var name = "wolf" + totalWolves;
var scrpt = document.createElement("SCRIPT");
document.body.appendChild(scrpt);
scrpt.setAttribute("id", name);
var script = document.getElementById(name);
script.innerHTML = "var rand3 = Math.floor(Math.random() * 100) + 1; var rand4 = Math.floor(Math.random() * 100) + 1; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = 'red'; context.fillRect(rand3, rand4, 10, 10); context.fill();";
}
for(var i=0; i<12; i++)
{
spawnWolves();
}
var maxWolves=9;
while(totalWolves < maxWolves)
{
spawnWolves();
}
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
<script>
</script>
</body>
</html>
The first loop will run until its internal counter i goes from 0 to 12 and will call the function exactly 12 times.
The second loop will run as long as the condition totalWolves < maxWolves is true. totalWolves is your counter you increase in your function and maxWolves is the limit when you want the loop to stop.
Because these 2 examples are added here one after another the second wont work. After the first one executes you will already have 12 wolves and the second loop will not enter because 12 < 9 is false.

change the image after refresh the page

I would like to change the image after refresh the page, but it doesn't work
Here is the javascript part
<script>
var theImages = [
"../images/casblanca.jpg",
"../images/casblanca2.jpg",
"../images/spot.jpg";
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("spotlight").src = theImages[x];
}
</script>
Here is the html main part
<nav class="spot" onload="changeImage()">
<h1>SPOTLIGHT</h1>
<img id="spotlight" width="1000" height="600" alt="">
</nav>
1) You are using and extra semi colon (;)
"../images/spot.jpg";
at the end of your last image. Go ahead and delete it.
2) Use the onload event in the body tag.
Here's a working solution. Hope it helps!
var theImages = [
"http://media.caranddriver.com/images/media/51/25-cars-worth-waiting-for-lp-ford-gt-photo-658253-s-original.jpg",
"https://carfromjapan.com/wp-content/uploads/2016/10/5-Best-Rated-Cars-of-2016.jpg",
"https://i.ytimg.com/vi/TzcS7Mcq2oA/maxresdefault.jpg"
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("spotlight").src = theImages[x];
}
<body onload="changeImage()">
<nav class="spot">
<h1>SPOTLIGHT</h1>
<img id="spotlight" width="1000" height="600" alt="">
</nav>
The onload attribute is not supported on the <nav> element. Try it on the <body>
There is also a syntax error in your image array. An unnecessary semicolon.
See working example below:
var theImages = [
"https://dummyimage.com/1000x600/000/fff&text=Image+1",
"https://dummyimage.com/1000x600/000/f0f&text=Image+2",
"https://dummyimage.com/1000x600/000/ff0&text=Image+3"
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("spotlight").src = theImages[x];
}
<body onload="changeImage()">
<nav class="spot" >
<h1>SPOTLIGHT</h1>
<img id="spotlight" width="1000" height="600" alt="">
</nav>
</body>
Separate CSS, JS and HTML.
Declare the varibles as
var theImages = [],
size, x;
Remove the onload() function.
Rewrite the random function as the following.
x = Math.floor(Math.random() * size);
Math.random() returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
Here Math.floor always return a value among 0,1,2.
Rewrite the code as the following.
size = theImages.length;
x = Math.floor(Math.random() * size);
document.getElementById("spotlight").src = theImages[x];
var theImages = [],
size, x;
theImages = [
"https://www.w3schools.com/w3css/img_car.jpg",
"https://www.w3schools.com/css/paris.jpg",
"https://www.w3schools.com/css/trolltunga.jpg"
];
size = theImages.length;
x = Math.floor(Math.random() * size);
document.getElementById("spotlight").src = theImages[x];
#spotlight {
width: 1000px;
height: 600px;
}
<h1>SPOTLIGHT</h1>
<img id="spotlight" alt="">

How to add link for the image using Javascript

How can I add a link for an image created using the following Javascript code. I tried some changes, but nothing worked.
Please change the following code to the code with a link. I want to link all images at http://idealbodyweights.com/.
<script type="text/javascript">
var image1 = new Image()
image1.src =="http://idealbodyweights.com/wp-content/uploads/2013/05/1.png"
var image2 = new Image()
image2.src = "http://idealbodyweights.com/wp-content/uploads/2013/05/2.png"
var image3 = new Image()
image3.src = "http://idealbodyweights.com/wp-content/uploads/2013/05/3.png"
var image4 = new Image()
image4.src = "http://idealbodyweights.com/wp-content/uploads/2013/05/4.png"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="720" height="90" name="slide" /></p>
<script type="text/javascript">
var step=4;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<4)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
I rewrote a little of your code so it doesn't use eval and so the <img> is fetched using document.getElementById.
...
<script type="text/javascript">
var imgsrc = [
'http://idealbodyweights.com/wp-content/uploads/2013/05/1.png', // 0
'http://idealbodyweights.com/wp-content/uploads/2013/05/2.png', // 1
'http://idealbodyweights.com/wp-content/uploads/2013/05/3.png', // 2
'http://idealbodyweights.com/wp-content/uploads/2013/05/4.png' // 3
],
imgcache = [], i;
for (i = 0; i < imgsrc.length; ++i) { // cache images
imgcache[i] = new Image();
imgcache[i].src = imgsrc[i];
}
</script>
</head>
<body>
<p><img src="images/pentagg.jpg"
width="720" height="90"
name="slide" id="slide" /></p>
<script type="text/javascript">
var step = -1, // set so first will be 0
img = document.getElementById('slide'); // get the <img>
function slideit() {
step = (step + 1) % imgsrc.length; // loop over 0, 1, 2, 3 (or more)
img.src = imgsrc[step]; // set src by array index
setTimeout(slideit, 2500); // repeat in 2500 ms
}
slideit();// start
</script>
...
Is it what you want? :D
<p>
<a href="http://idealbodyweights.com/">
<img src="images/pentagg.jpg" width="720" height="90" name="slide" />
</a>
</p>

Categories