I have this inside index.html
<body>
<script>
window.onload=function() {
let videoDiv = createVideoDiv()
document.getElementById("contentVideo").appendChild(videoDiv);
document.addEventListener("keydown", function(inEvent){
controlVideo(inEvent.keyCode);
});
}
</script>
<div id="progressBarWrapper">
<div id="progressBar"></div>
</div>
<div id="contentVideo"></div>
</body>
and this css
#progressBarWrapper {
width: 100%;
height:15px;
background-color: black;
}
#progressBar {
width: 0%;
height: 15px;
background-color: green;
}
this is how the video div is created:
function createVideoDiv() {
var video = document.createElement("VIDEO");
video.setAttribute('controls', '');
//video.setAttribute('autoplay', '');
video.setAttribute('preload', 'auto');
video.setAttribute('width', larguraVideo);
video.setAttribute('id', 'video');
var source = document.createElement("SOURCE");
source.setAttribute('src', obterVideoClicado());
source.setAttribute('type', 'video/mp4');
video.addEventListener('progress', function() {
var range = 0;
var bf = this.buffered;
var time = this.currentTime;
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
setTimeout(ajustarProgressBar, 40, loadPercentage * 100);
});
video.addEventListener('loadeddata', function() {
var myBar = document.getElementById("progressBarWrapper");
myBar.style = "display:none;";
video.play();
});
video.appendChild(source);
return video;
}
this is how the progress bar is adjusted
function ajustarProgressBar(valor) {
var progressBar = document.getElementById("progressBar");
progressBar.style.width = valor + "%";
}
Even the progress bar is being fired by
setTimeout(ajustarProgressBar, 40, loadPercentage * 100);
the progress bar is not updating and stays 0% all the time.
The progress bar is to be adjusted by the video download progress.
The video progress is working fine. I have printed that to console and the values are changing as the video download progresses.
You have to pass param to function:
var valor = loadPercentage * 100;
var delay = 100;
setTimeout(() => ajustarProgressBar(valor), delay);
--Edit
Your video progress event listener would now look like:
video.addEventListener('progress', function() {
var range = 0;
var bf = this.buffered;
var time = this.currentTime;
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
var valor = loadPercentage * 100;
var delay = 100;
setTimeout(() => ajustarProgressBar(valor), delay);
});
The setTimeout function takes 2 parameters:
The function to call after the delay time
The delay time in milliseconds
So to call your function you must make a function that will call your function like this:
setTimeout(() => ajustarProgresBar(loadPercentage * 100), 40);
So in your code it might look like this:
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
setTimeout(() => ajustarProgressBar(loadPercentage*100), 40);
Related
I have a function that adds random images to my divs that disappear over time and create a mouse trail. My issue is: there are double images.
I'd like to add something that checks if the background url is already located on the page and if that's the case, skips to the next in the array and check it again until until it comes across one that is not there. So like a loop that refreshes every time a 'trail' is being created.
Maybe I am asking for something that won't work? What if all the images are already on the page? I don't really have an answer for it and I also don't have an idea how to solve that problem yet.
For now I tried adding a counter that checks the usedImages and counts them, but it seems to have flaws and I am unsure where to look or how to fix it. Does anyone have any tips on how to do this? Is it even possible?
My fiddle
var bgImages = new Array(
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/schraegluftbild-1024x725.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/pikto-608x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/lageplan-945x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhauser-Esch-Modell-2-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/DSCN3481-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/zoom-in-3_ASTOC-1024x683.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2016/07/IMG_1345-1024x768.jpg"
);
const numberOfImages = 10;
const timesPerSecond = .1;
var usedImages = {};
var usedImagesCount = 0;
function preloadImages(images) {
for (i = 0; i < images.length; i++) {
let l = document.createElement('link')
l.rel = 'preload'
l.as = 'image'
l.href = images[i]
document.head.appendChild(l);
}
}
function animate(e) {
var image = document.createElement('div');
image.classList.add('trail');
var sizew = 200;
var sizeh = 200;
image.style.transition = '3s ease';
image.style.position = 'fixed';
image.style.top = e.pageY - sizeh / 2 + 'px';
image.style.left = e.pageX - sizew / 2 + 'px';
image.style.width = sizew + 'px';
image.style.height = sizeh + 'px';
var random = Math.floor(Math.random() * (bgImages.length));
if (!usedImages[random]) {
image.style.backgroundImage = "url(" + bgImages[random] + ")";
usedImages[random] = true;
usedImagesCount++;
if (usedImagesCount === bgImages.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
animate(e);
}
console.log(usedImages);
console.log(usedImagesCount);
image.style.backgroundSize = 'cover';
image.style.pointerEvents = 'none';
image.style.zIndex = 1;
document.body.appendChild(image);
//opacity and blur animations
window.setTimeout(function() {
image.style.opacity = 0;
image.style.filter = 'blur(20px)';
}, 40);
window.setTimeout(function() {
document.body.removeChild(image);
}, 2100);
};
window.onload = function() {
preloadImages(bgImages);
var wait = false;
window.addEventListener('mousemove', function(e) {
if (!wait) {
wait = true;
setTimeout(() => {
wait = false
}, timesPerSecond * 800);
animate(e);
}
});
};
I have a repeat function which runs on a button on-click event, however it's not working properly. Maybe because there are too many setIntervals running although I tried to clear them all. I also made sure to reset the variables used back to their initial values, however the moving circle keeps showing up faded when the shoot again button is pressed, so I'm assuming there's an issue with the setInterval, however, I don't know what it is.It's also not drawing the basketball again.
var level = prompt("Type 1 for hard, 2 for medium, and 3 for easy.")
var dt = level / 100;
var ctx = canvas.getContext("2d");
var intervalId2;
var intervalId1;
//Initializing Variables
var dt = level / 100;
const PI = 3.14;
var r = 20;
var x = r + 1;
var y = 500 / 1.2;
var a = 1;
var shift = 380;
var leftshift = 35;
var xc = 145;
var yc = 300;
var rc = 50;
var dxc = 95;
var dyc = 300;
var theta = 0;
var resetVars = function() {
dt = 0.01;
var x = r + 1;
var y = 500 / 1.2;
var xc = 145;
var yc = 300;
var dxc = 95;
var dyc = 300;
var theta = 0;
};
//resetVars();
var reset = function() {
ctx.clearRect(0, 0, 800, 800);
drawHoop()
};
//Interval Id to eventually clear it to stop this to shoot
var intervalID = setInterval(moveCirc, 10000 * dt);
var count = 0;
//shoot when spacebar is pressed
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
var repeat = function() {
reset();
clearInterval(intervalID);
clearInterval(intervalId2);
clearInterval(intervalId1);
resetVars();
drawBasketball();
drawHoop();
moveCirc();
intervalID = setInterval(moveCirc, 10000 * dt);
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
};
<html>
<canvas id="canvas" width="1000" height="500"> </canvas>
<body style="background-color:powderblue;">
<p id="count"></p>
<button id="again" onclick="repeat()"> Shoot Again </button>
</body>
This should make a stop button for a repeating function
<script>
var int=self.setInterval(function, 60000);
</script>
<!-- Stop Button -->
Stop
I have a function where the user sort of "scratching" a surface when he drags the mouse over it, reviling content underneath this surface. I want to count how many seconds he dragged the mouse, and when he reaches 5 seconds - do something. If he lets go after, for example, 3 seconds, the count should stop and resume from 3d second when he resumes dragging. I tried to do it with setInterval and add 1 to seconds counter every 1000 ms, but no matter what I've tried - I'm either getting some crazy numbers in the counter or it just stays on 0. Here's my code:
var interval, info;
var totalSeconds = 0;
function init()
{
...more vars declaration and initialization
function scratchOff(x, y)
{
mainctx.save();
mainctx.beginPath();
mainctx.arc(x,y,radius,0,Math.PI*2,false);
mainctx.clip();
mainctx.drawImage(bottomImage, 0, 0);
mainctx.restore();
}
$('#overlay').mousedown(function(e){
isMouseDown = true;
var relX = e.pageX;
var relY = e.pageY;
scratchOff(relX, relY, true);
});
$('#overlay').mousemove(function(e){
var relX = e.pageX;
var relY = e.pageY;
overlayctx.clearRect(0,0,canvasWidth,canvasHeight);
overlayctx.drawImage(coinImage, relX-radius, relY-radius);
if (isMouseDown) {
scratchOff(relX, relY, false);
countSeconds(); // - THIS CALLS FOR THE FUNCTION THAT IS SUPPOSED
// TO COUNT SECONDS ONCE THE USER STARTS DRAGGING THE MOUSE
}
});
$('#overlay').mouseup(function(e){
isMouseDown = false;
clearInterval(interval);
});
var mainctx = $('canvas')[0].getContext('2d');
var radius = 10;
topImage.onload = function(){
mainctx.drawImage(topImage, 0, 0);
};
topImage.src = "images/oie_canvas.png";
}
// THIS IS THE FUNCTION THAT'S SUPPOSED TO COUNT SECONDS
function countSeconds() {
interval = setInterval(function(){
totalSeconds = totalSeconds++;
info.innerHTML = totalSeconds;
if(totalSeconds >= 5) clearInterval(interval);
}, 1000);
}
How can I make it work?
You would start a timer of 1 sec, which monitor your isMouseDown flag and start counting, when you reach 5 sec you go for your action, no need to call the countSeconds every time.
Here is an example:
EDITED
$(function() {
setInterval(function(){
if(isMouseDown) {
totalSeconds++;
}
if(totalSeconds== 5) {
//do your action;
totalSeconds = 0;
}
info.innerHTML = totalSeconds;
}, 1000);
} );
var isMouseDown = false;
function init()
{
... your code
}
EDITED 2
Full Example
var topImage = new Image();
var bottomImage = new Image();
var coinImage = new Image();
bottomImage.src = "http://i58.tinypic.com/2i093ia.jpg";
coinImage.src = "http://i61.tinypic.com/30acmtt.png";
var info;
var interval;
var totalSeconds = 0;
$(function() {
setInterval(function(){
if(isMouseDown) {
totalSeconds++;
}
if(totalSeconds== 5) {
alert("5 sec");
totalSeconds = 0;
}
info.innerHTML = totalSeconds;
}, 1000);
} );
var isMouseDown = false;
function init()
{
var canvasWidth = $('#myCanvas').width();
var canvasHeight = $('#myCanvas').height();
$('body').append('<canvas id="overlay" width="'+canvasWidth+'" height="'+canvasHeight+'" />');
var overlayctx = $('canvas')[1].getContext('2d');
overlayctx.drawImage(coinImage, 0,0);
info = document.getElementById('info');
function scratchOff(x, y)
{
mainctx.save();
mainctx.beginPath();
mainctx.arc(x,y,radius,0,Math.PI*2,false);
mainctx.clip();
mainctx.drawImage(bottomImage, 0, 0);
mainctx.restore();
}
$('#overlay').mousedown(function(e){
isMouseDown = true;
var relX = e.pageX;
var relY = e.pageY;
scratchOff(relX, relY, true);
});
$('#overlay').mousemove(function(e){
var relX = e.pageX;
var relY = e.pageY;
overlayctx.clearRect(0,0,canvasWidth,canvasHeight);
overlayctx.drawImage(coinImage, relX-radius, relY-radius);
if (isMouseDown) {
scratchOff(relX, relY, false);
countSeconds();
}
});
$('#overlay').mouseup(function(e){
isMouseDown = false;
clearInterval(interval);
});
var mainctx = $('canvas')[0].getContext('2d');
var radius = 10;
topImage.onload = function(){
mainctx.drawImage(topImage, 0, 0);
};
topImage.src = "http://i61.tinypic.com/xpzbx0.png";
}
I'm having a bit of trouble I am making my own controls for a html5 video player. I have got everything working correctly but I would like for my slider to have a specified colour left of the thumb and a different colour right of the thumb. i Have seen another example on here that almost does it with jquery but I can only get it working onclick and not progessing automatically with the video. I am new to javascript and could really do with the help getting this to work.
<script>
var
vid,
playbtn,
mutebtn,
fullscreenbtn,
seekslider,
volumeslider,
curtimetext,
durtimetext;
function intializePlayer(){
//Set object references
vid = document.getElementById("my_player");
playbtn = document.getElementById("playpausebtn");
mutebtn = document.getElementById("mutebtn");
fullscreenbtn = document.getElementById("fullscreenbtn");
seekslider = document.getElementById("seekslider");
volumeslider = document.getElementById("volumeslider");
curtimetext = document.getElementById("curtimetext");
durtimetext = document.getElementById("durtimetext");
//Add event listeners
playbtn.addEventListener("click",playPause,false);
mutebtn.addEventListener("click",vidmute,false);
fullscreenbtn.addEventListener("click",toggleFullScreen,false);
seekslider.addEventListener("change",vidSeek,false);
volumeslider.addEventListener("change",setvolume,false);
vid.addEventListener("timeupdate",seektimeupdate,false);
}
window.onload = intializePlayer;
function playPause(){
if(vid.paused){
vid.play();
playbtn.style.background = "url(images/pause.png)";
} else {
vid.pause();
playbtn.style.background = "url(images/play.png)";
}
}
function vidSeek(){
var seekto = vid.duration * (seekslider.value / 100);
vid.currentTime = seekto;
}
function seektimeupdate() {
var nt = vid.currentTime * (100 / vid.duration);
seekslider.value = nt;
var curmins = Math.floor(vid.currentTime / 60);
var cursecs = Math.floor(vid.currentTime - curmins * 60);
var durmins = Math.floor(vid.duration / 60);
var dursecs = Math.floor(vid.duration - durmins * 60);
if(cursecs < 10){ cursecs = "0"+cursecs; }
if(dursecs < 10){ dursecs = "0"+dursecs; }
if(curmins < 10){ curmins = "0"+curmins; }
if(durmins < 10){ durmins = "0"+durmins; }
curtimetext.innerHTML = curmins+":"+cursecs;
durtimetext.innerHTML = durmins+":"+dursecs;
}
function vidmute(){
if(vid.muted){
vid.muted = false;
mutebtn.style.background = "url(images/volume.png)";
volumeslider.value = 100;
} else {
vid.muted = true;
mutebtn.style.background = "url(images/mute.png)";
volumeslider.value = 0;
}
}
function setvolume(){
vid.volume = volumeslider.value / 100;
}
function toggleFullScreen(){
if(vid.requestFullScreen){
vid.requestFullScreen();
} else if(vid.webkitRequestFullScreen){
vid.webkitRequestFullScreen();
} else if(vid.mozRequestFullScreen){
vid.mozRequestFullScreen();
}
}
</script>
I think what you're trying to do is update the "seektimeupdate" function every second. To do this you can use a thing called "setInterval". The code would look something like this.
var updateBar = setInterval(function(){
//You put the code you want to perform here
seektimeupdate();
},1000)
What the "1000" means is the delay, in milliseconds, between each time the code is fired. You can think of "setInterval" as a for loop that performs its code at a set rate, specified by the number at the end.
Sorry if I misunderstood your question and if you want more help on the "setInterval" function then see W3 school's documentation on it here
EDIT:
This Code works, assuming you can get the duration of the movie in seconds and the current time of the movie in seconds. The only problem you might encounter is changing the slider, depending on how the user moves the thumb or if they pause the movie. I would suggest using variables to buffer the function.
(NOTE): Just replace the jQuery in the jsFiddle link you gave me in the comments with this.
var movie = {
//duration of movie, in seconds
duration:1000,
//current time in movie, in seconds
currentTime:0
}
var update = setInterval(function(){
movie.currentTime += 1;
var val = movie.currentTime/movie.duration;
$("#range").css('background-image',
'-webkit-gradient(linear, left top, right top, '
+ 'color-stop(' + val + ', #94A14E), '
+ 'color-stop(' + val + ', #C5C5C5)'
+ ')'
);
},1000);
I hope someone can help me with this.
When my HTML Textbox is clicked, I would like a Div to expand in length using preferably only JavaScript. I attached a picture to show in more depth. Again, If anyone could help me - I'll be greatfull.
Something like this should be sufficient, HTML:
<input type = "text" style = "width: 500px;" onfocus = "expand();" onblur = "collapse();">
<div id = "yourdiv"></div>
CSS:
#yourdiv {
margin-top: 0px;
background-color: rgb(0, 162, 232);
width: 500px;
height: 0px;
}
JavaScript:
var t;
function expand() {
var dv = document.getElementById("yourdiv");
var duration = 500; //number of milliseconds for animation; 1000ms = 1s.
var stepDur = Math.floor(duration / 200); //200px is our goal height here
var curHeight = parseInt(dv.style.height.substr(0, dv.style.height.length - 2), 10); //current height of dv
if(isNaN(curHeight)) {
curHeight = 0;
}
clearTimeout(t); //make sure no other animation is happening
function doAnim() {
if(curHeight >= 200) {
//we're done!
return;
}
curHeight ++;
dv.style.height = curHeight + "px";
t = setTimeout(doAnim, stepDur);
}
doAnim();
}
function collapse() {
var dv = document.getElementById("yourdiv");
var duration = 500; //number of milliseconds for animation; 1000ms = 1s.
var stepDur = Math.floor(duration / 200);
var curHeight = parseInt(dv.style.height.substr(0, dv.style.height.length - 2), 10); //current height of dv
clearTimeout(t); //make sure no other animation is happening
function doAnim() {
if(curHeight <= 0) {
//we're done!
return;
}
curHeight --;
dv.style.height = curHeight + "px";
t = setTimeout(doAnim, stepDur);
}
doAnim();
}
Demo: little link.
I hope that helped!