JavaScript : animation for a div - javascript

I want to animate a div (say height 50 px and width 50 px) from left to right in the browser.
I can share my html css part here:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box{
width:100px;
height:100px;
position: absolute;
}
.blue{
background:#00f;
}
.position{
margin-top: 50px;
}
</style>
</head>
<body>
<div class="box blue position" id="move_box"> </div>
<script>
</script>
</body>
</html>
How can I animate the div from left to right according to the condition "moves 10 pixels right and 10 pixels down per second"?
Note: only in JavaScript.
My script:
<script>
var box = document.getElementById('move_box'),
boxPos = 0,
boxLastPos = 0,
boxVelocity = 0.01,
limit = 300,
lastFrameTimeMs = 0,
maxFPS = 60,
delta = 0,
timestep = 1000 / 60,
fps = 60,
framesThisSecond = 0,
lastFpsUpdate = 0,
running = false,
started = false,
frameID = 0;
function update(delta) {
boxLastPos = boxPos;
boxPos += boxVelocity * delta;
// Switch directions if we go too far
if (boxPos >= limit || boxPos <= 0) boxVelocity = -boxVelocity;
}
function draw(interp) {
box.style.left = (boxLastPos + (boxPos - boxLastPos) * interp) + 'px';
box.style.top = (boxLastPos + (boxPos - boxLastPos) * interp) + 'px';
console.log(box.style.top);
}
function panic() {
delta = 0;
}
function begin() {
}
function end(fps) {
/*box.style.backgroundColor = 'blue';*/
}
function stop() {
running = false;
started = false;
cancelAnimationFrame(frameID);
}
function start() {
if (!started) {
started = true;
frameID = requestAnimationFrame(function(timestamp) {
draw(1);
running = true;
lastFrameTimeMs = timestamp;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
frameID = requestAnimationFrame(mainLoop);
});
}
}
function mainLoop(timestamp) {
// Throttle the frame rate.
if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
frameID = requestAnimationFrame(mainLoop);
return;
}
delta += timestamp - lastFrameTimeMs;
lastFrameTimeMs = timestamp;
begin(timestamp, delta);
if (timestamp > lastFpsUpdate + 1000) {
fps = 0.25 * framesThisSecond + 0.75 * fps;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
}
framesThisSecond++;
var numUpdateSteps = 0;
while (delta >= timestep) {
update(timestep);
delta -= timestep;
if (++numUpdateSteps >= 240) {
panic();
break;
}
}
draw(delta / timestep);
end(fps);
frameID = requestAnimationFrame(mainLoop);
}
start();
</script>

Check that:
var i = 1;
var div = document.getElementById('move_box');
function myLoop() {
setTimeout(function() {
div.style.top = i * 10 + 'px'
div.style.left = i * 10 + 'px'
i++;
if (i < 5) {
myLoop();
}
}, 1000)
}
myLoop(); // start the loop
.box {
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
}
.blue {
background: #00f;
}
.position {
margin-top: 50px;
}
<div class="box blue position" id="move_box"> </div>
JSFiddle

Related

JavaScript: array values are automatically getting deleted

I am making an image slider/ carousel. If you drag it, the images will get momentum and will keep on moving for sometime. There are few issues, one of them is getting the following error frequently: "glide.js:104 Uncaught TypeError: Cannot read property '1' of undefined". JavaScript here is supposed to access a value that is inside an array, but since the array is empty, i'm getting this error. However, the array shouldn't be empty, as the code that empties the array, comes later. Project
var projectContainer = document.querySelector(".project-container")
var projects = document.querySelectorAll(".project")
// exProject is declared so that every project has same transalte to refer to instead of referring to their individual transalations
var exProject = projects[0]
var style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
// after dragging, do not add force if mouse has not been moved for pauseTime milliseconds
pauseTime = 40
lastMousePositions = []
//this will set margin to 80, i thought this is better than hardcoding
elementAOffset = projects[0].offsetLeft;
elementBOffset = projects[1].offsetLeft;
elementAWidth = parseInt(getComputedStyle(projects[0]).width)
margin = (elementBOffset - (elementAOffset + elementAWidth))
//projects will teleport to other side if they hit either of the boundary
LeftSideBoundary = -(elementAWidth)
RightSideBoundary = (elementAWidth * (projects.length)) + (margin * (projects.length))
RightSidePosition = RightSideBoundary - elementAWidth;
//how often to update speed (in milliseconds)
intervalTime = 15
//how much speed is lost at every interTime milliseconds
frictionPerMilliseconds = (20 / 1000);
frictionPerMilliseconds *= intervalTime * 5;
mouseInitialPosition = 0;
mouseIsDown = false
startTime = 0;
speed = 0;
mousemoving = false
projectContainer.addEventListener("mousedown", e => {
mouseInitialPosition = e.clientX
mouseIsDown = true;
startDate = new Date();
startTime = startDate.getTime();
lastMousePositions.push(e.clientX)
speed = 0
})
projectContainer.addEventListener("mousemove", e => {
if (!mouseIsDown) return;
distanceTravelled = e.clientX - mouseInitialPosition
if (speed === 0) {
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + ((distanceTravelled))) + 'px)';
shiftPosition(project, distanceTravelled)
})
}
if ((new Date()).getTime() - lastMousePositions[lastMousePositions.length - 1][1] > 50) {
lastMousePositions = []
}
pushToMousePositions(e.clientX)
})
projectContainer.addEventListener("mouseup", e => {
dragEnd(e);
})
projectContainer.addEventListener("mouseleave", e => {
dragEnd(e);
})
function dragEnd(e) {
finalPosition = e.clientX;
distanceTravelled = finalPosition - mouseInitialPosition
endDate = new Date();
endTime = endDate.getTime();
timeElapsed = (endTime - startTime) / 1000
mouseIsDown = false;
tempSpeed = distanceTravelled / timeElapsed
tempSpeed = (tempSpeed / 1000) * 15
if (tempSpeed < 0 && speed < 0) {
if (tempSpeed < speed) {
speed = tempSpeed
}
} else if (tempSpeed > 0 && speed > 0) {
if (tempSpeed > speed) {
speed = tempSpeed
}
} else {
speed = tempSpeed
}
if (lastMousePositions.length === 0) {
console.log("error gonna pop up")
}
if (endTime - (lastMousePositions[lastMousePositions.length - 1])[1] >= pauseTime) {
speed = 0
}
mouseExit(e)
intervalFunction = setInterval(move, intervalTime)
}
function mouseExit(e) {
mouseIsDown = false
lastMousePositions = []
var style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + (exProject.currentTranslationX) + 'px)'
shiftPosition(project, 0)
})
}
function move() {
if (speed === 0) {
clearInterval(intervalFunction)
} else if (Math.abs(speed) <= frictionPerMilliseconds) {
style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + (speed)) + 'px)'
shiftPosition(project, 0)
})
speed = 0
} else {
style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + (speed)) + 'px)'
shiftPosition(project, 0)
})
speed < 0 ? speed += frictionPerMilliseconds : speed -= frictionPerMilliseconds;
}
}
function pushToMousePositions(positionToPush) {
if (lastMousePositions.length < 50) {
lastMousePositions.push([positionToPush, (new Date()).getTime()])
} else {
lastMousePositions.shift();
lastMousePositions.push([positionToPush, (new Date()).getTime()])
}
}
function shiftPosition(project, mouseMovement) {
//projectVisualPosition is relative to the left border of container div
projectVisualPosition = project.offsetLeft + (exProject.currentTranslationX + mouseMovement)
tempStyle = window.getComputedStyle(project)
if (projectVisualPosition < LeftSideBoundary) {
project.style.left = ((parseInt(tempStyle.left) + RightSidePosition + 350) + 'px')
}
if (projectVisualPosition > RightSidePosition) {
project.style.left = ((parseInt(tempStyle.left)) - (RightSidePosition + elementAWidth)) + 'px'
}
}
*,
*::before,
*::after {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-size: 0px;
user-select: none;
font-size: 0;
}
body {
position: relative;
}
.project-container {
font-size: 0px;
position: relative;
width: 1500px;
height: 400px;
background-color: rgb(15, 207, 224);
margin: auto;
margin-top: 60px;
white-space: nowrap;
overflow: hidden;
padding-left: 40px;
padding-right: 40px;
}
.project {
font-size: 100px;
margin: 40px;
display: inline-block;
height: 300px;
width: 350px;
background-color: red;
border: black 3px solid;
user-select: none;
position: relative;
}
<div class="project-container">
<div class="project">1</div>
<div class="project">2</div>
<div class="project">3</div>
<div class="project">4</div>
<div class="project">5</div>
<div class="project">6</div>
<div class="project">7</div>
<div class="project">8</div>
</div>
The problem is this:
projectContainer.addEventListener("mouseleave", (e) => {
dragEnd(e);
});
You're calling dragEnd(e) when the cursor leaves projectContainer. That can happen while the lastMousePositions array is still empty.
Option 1: Don't call dragEnd(e) on the mouseleave event
Option 2: Inside the dragEnd(e) function, check that the array is not empty before you try to access its elements:
if (lastMousePositions.length !== 0) {
if (
endTime - lastMousePositions[lastMousePositions.length - 1][1] >=
pauseTime
) {
speed = 0;
}
}

Generate one percent width every second

Ok I'm trying to add every one second a 1% width with a background colour, but it appears in oneblock...
Can someone help me ?
Thank you all
Here is my code :
setTimeout(function() {
var percentage = 1;
for (var i = 0; i < 10; i++) {
var blabla = i + percentage
console.log(blabla)
document.getElementById("position").style.width = blabla + "%";
document.getElementById("position").style.backgroundColor = "blue";
document.getElementById("position").style.height = "20px";
}
}, 1000);
}
Rather than a loop, use setInterval
const increment = 1;
const tick = 1000;
let percent = 0;
const timer = setInterval(() => {
const div = document.querySelector('#position');
percent += increment;
div.style.width = `${percent}%`;
if ( percent >= 100 ) clearInterval(timer);
}, tick);
#position {
background-color: blue;
height: 20px;
width: 1%;
}
<div id="position"></div>
Maybe lets do this for several progress bars.
const timers = [];
const doTimer = (id, { tick = 1000, increment = 1 } = {}) => {
let percent = 0;
timers[id] = setInterval(() => {
const div = document.querySelector(`#${id}`);
percent += increment;
div.style.width = `${percent}%`;
div.innerHTML = `${percent}%`;
if ( percent >= 100 ) clearInterval(timers[id]);
}, tick);
};
doTimer('position');
doTimer('data', { tick: 500 });
doTimer('another', { increment: 5 });
#position, #data, #another {
background-color: blue;
height: 20px;
width: 1%;
}
#data {
background-color: red;
}
#another {
background-color: yellow;
}
<div id="position"></div>
<div id="data"></div>
<div id="another"></div>
document.getElementById("position").style.backgroundColor = "blue";
var i = 0;
function loop(){
i++;
document.getElementById("position").style.width = i+"%";
document.getElementById("position").innerHTML = i+"%";
if(i<10) {
setTimeout(function() {
loop();
}, 1000);
}
}
loop();
<div id="position"></div>

I wanna repeat function infinite but i couldn't

I wanna do some effect to my background so i tought i can add some shapes flying around but i do only 1 shape i cant loop or anything
i tried call function more than a one time but it doesnt help
function animasyon(a) {
window.onload=function(){
var id = setInterval(anim,5);
$('body').append('<div class=shape></div>');
$('body').append('<div class=shape></div>');
var kutu = document.getElementsByClassName("shape");
var pos = 0;
var x = window.innerWidth;
var y = window.innerHeight;
var borderSize = Math.floor(Math.random() * 3 ) + 1;
var ySize = Math.floor(Math.random() * y ) + 1;
var Size = Math.floor(Math.random() * 30 ) + 5;
var yon = Math.floor(Math.random() *2)+1;
var dolu = Math.floor(Math.random() *2)+1;
if (ySize > 50) { ySize-=20; }
function anim(){
if (pos == x) {
clearInterval(id);
document.getElementById("shape").remove();
}else{
pos++;
kutu[a].style.position = "absolute";
kutu[a].style.border = "solid rgb(119,38,53) "+borderSize+"px";
kutu[a].style.left = pos+"px";
kutu[a].style.width = Size+"px";
kutu[a].style.height = Size+"px";
if (yon == 1) { ySize-=0.2; } else { ySize+=0.2; }
if (dolu==1) {kutu[a].style.background = "rgb(119,38,53)";}
if (kutu[a].offsetTop < 0 || kutu[a].offsetTop > y-30) {document.getElementById("shape").remove();}
kutu[a].style.top = ySize+"px";
}
}
}
}
animasyon(0);
Try Calling 'anim' function in this way
setInterval(function(){anim()},5);
Your problem is that you are assigning window.onload function a value inside the function animasyon
window.onload holds only 1 function. If you call animation function more than once, then the last one will overwrite the first one.
Edit: You need to separate your animation logic from the page load logic. They are completely separate things.
Here is an example of adding multiple objects and animating each separately.
// HTML
<div id="container">
<div id="ball"></div>
<div id="ball2"></div>
<div id="ball3"></div>
<div id="ball4"></div>
</div>
// CSS
#ball, #ball2, #ball3, #ball4 {
background: red;
border: 1px solid #FAFDFA;
display: inline-block;
width: 1em;
height: 1em;
border-radius: 2em;
position: absolute;
}
#ball2 {
background: blue;
}
#ball3 {
background: green;
}
#ball4 {
background: purple;
}
#container {
width: 512px;
height: 512px;
background: black;
position: relative;
}
// JS
const container = document.getElementById('container');
const stageWidth = 512;
const stageHeight = 512;
const makeFall = (elementId) => {
// this function makes an enlement fall in random direction
const animationSpeed = 4;
// your onload function
const ball = document.getElementById(elementId);
let directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
let directionY = Math.random() * animationSpeed;
const setRandomStart = () => {
ball.style.top = '10px';
ball.style.left = (Math.random() * (stageWidth / 2)) + 'px';
directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
directionY = Math.random() * animationSpeed;
}
setRandomStart();
let animationInterval = setInterval(() => {
let px = parseFloat(ball.style.left);
let py = parseFloat(ball.style.top);
px += directionX;
py += directionY;
if (px > stageWidth - 20 || py > stageHeight - 20 || px < -20) {
setRandomStart();
} else {
ball.style.left = px + 'px';
ball.style.top = py + 'px';
}
}, 48);
}
// In Your onload function you can add the elements and then animate
makeFall('ball');
makeFall('ball2');
makeFall('ball3');
makeFall('ball4');
https://jsfiddle.net/753oL8re/4/

how to make progress Bar with numbers

i have a progress bar which has to finish at 100%, and this moment the number shows this progress, the problem is this number is 1.5(it has to show 0.1, 0,2 and so on till number - 1.5) and I don't know how bind the progress bar with this number
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 20);
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
x.innerHTML = width + "%";
}
}
});
Do width/100 and use toFixed() to determine the number of decimals.
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 20);
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
x.innerHTML = ((width / 100).toFixed(1)) + "%";
}
}
});
#load {
position: fixed;
height: 100%;
display: flex;
align-items: center;
background-color: #000;
color: #fff;
font-size: 50px;
justify-content: flex-end;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="load" />
This is more a math problem than a scripting one...
You have to tell the script that 1.5 is 100%.
I only added one line to your script in order to change the inner HTML displayed.
var showNumber = (1.5/100)*width;
x.innerHTML = showNumber.toFixed(1);
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 200); // Setted a longer delay...
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
var showNumber = (1.5/100)*width;
x.innerHTML = showNumber.toFixed(1); // Only one decimal.
}
}
});
#load{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="load"></div>

face's detected save image, instead of draw image(glasses)

So im attempting to use lulu's CCV JavaScript library and this code example seen here that draws glasses over a detected face: enter link description here
But instead of drawing glasses I would like to be able to detect the face, and draw a rectangle around it, then save it in the web browser as a variable.
In the face.html file there is a line which I believe draws the glasses to the detected face
for (i = App.comp.length; i--; ) {
ctx.strokeRect(App.glasses, (App.comp[i].x - w / 2) * m, (App.comp[i].y - w / 2) * m, (App.comp[i].width + w) * m, (App.comp[i].height + w) * m);
}
}
};
I have tried replaced that line with this code snippet:
ctx.strokeRect(comp[i].x, comp[i].y, comp[i].width, comp[i].height);
It does draw a rectangle, but a small one in the corner of the screen. I'm lost lost as where to go from here.
The entire code for the html page is seen here:
<pre>
<!DOCTYPE html>
<html lang="en">
<!-- Adapted to work with the getUserMedia API using code from http://wesbos.com/html5-video-face-detection-canvas-javascript/ -->
<head>
<meta charset="utf-8">
<title>HTML5 Face Detection - JavaScript getUserMedia API and Groucho Marx glasses!</title>
<style>
body {
font-family: sans-serif;
font-size: 17px;
line-height: 24px;
color: #fff;
width: 100%;
height: 100%;
margin: 0;
text-align: center;
background-color: #111;
}
#info {
position: absolute;
width: 100%;
height: 30px;
top: 50%;
margin-top: -15px;
}
#output {
width: auto;
height: 100%;
background: black;
-webkit-transform: scale(-1, 1);
}
</style>
</head>
<body>
<p id="info">Please allow access to your camera!</p>
<canvas id="output"></canvas>
<script src="ccv.js"></script>
<script src="face.js"></script>
<script>
// requestAnimationFrame shim
(function() {
var i = 0,
lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
while (i < vendors.length && !window.requestAnimationFrame) {
window.requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
i++;
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 1000 / 60 - currTime + lastTime),
id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
}());
var App = {
start: function(stream) {
App.video.addEventListener('canplay', function() {
App.video.removeEventListener('canplay');
setTimeout(function() {
App.video.play();
App.canvas.style.display = 'inline';
App.info.style.display = 'none';
App.canvas.width = App.video.videoWidth;
App.canvas.height = App.video.videoHeight;
App.backCanvas.width = App.video.videoWidth / 4;
App.backCanvas.height = App.video.videoHeight / 4;
App.backContext = App.backCanvas.getContext('2d');
var w = 300 / 4 * 0.8,
h = 270 / 4 * 0.8;
App.comp = [{
x: (App.video.videoWidth / 4 - w) / 2,
y: (App.video.videoHeight / 4 - h) / 2,
width: w,
height: h,
}];
App.drawToCanvas();
}, 500);
}, true);
var domURL = window.URL || window.webkitURL;
App.video.src = domURL ? domURL.createObjectURL(stream) : stream;
},
denied: function() {
App.info.innerHTML = 'Camera access denied!<br>Please reload and try again.';
},
error: function(e) {
if (e) {
console.error(e);
}
App.info.innerHTML = 'Please go to about:flags in Google Chrome and enable the "MediaStream" flag.';
},
drawToCanvas: function() {
requestAnimationFrame(App.drawToCanvas);
var video = App.video,
ctx = App.context,
backCtx = App.backContext,
m = 4,
w = 4,
i,
comp;
ctx.drawImage(video, 0, 0, App.canvas.width, App.canvas.height);
backCtx.drawImage(video, 0, 0, App.backCanvas.width, App.backCanvas.height);
comp = ccv.detect_objects(App.ccv = App.ccv || {
canvas: App.backCanvas,
cascade: cascade,
interval: 4,
min_neighbors: 1
});
if (comp.length) {
App.comp = comp;
}
for (i = App.comp.length; i--; ) {
ctx.strokeRect(App.glasses, (App.comp[i].x - w / 2) * m, (App.comp[i].y - w / 2) * m, (App.comp[i].width + w) * m, (App.comp[i].height + w) * m);
}
}
};
App.glasses = new Image();
App.glasses.src = 'glasses.png';
App.init = function() {
App.video = document.createElement('video');
App.backCanvas = document.createElement('canvas');
App.canvas = document.querySelector('#output');
App.canvas.style.display = 'none';
App.context = App.canvas.getContext('2d');
App.info = document.querySelector('#info');
navigator.getUserMedia_ = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
try {
navigator.getUserMedia_({
video: true,
audio: false
}, App.start, App.denied);
} catch (e) {
try {
navigator.getUserMedia_('video', App.start, App.denied);
} catch (e) {
App.error(e);
}
}
App.video.loop = App.video.muted = true;
App.video.load();
};
App.init();
</script>
</body>
</html>
</pre>
Any ideas?
var x_offset = 0, y_offset = 0, x_scale = 1, y_scale = 1;
if (App.video.Width * App.video.Height > localVideo.videoWidth * localVideo.clientHeight) {
x_offset = (localVideo.clientWidth - localVideo.clientHeight * localVideo.videoWidth / localVideo.videoHeight) / 2;
} else {
y_offset = (localVideo.clientHeight - localVideo.clientWidth * localVideo.videoHeight / localVideo.videoWidth) / 2;
}
x_scale = (localVideo.clientWidth - x_offset * 2) / localVideo.videoWidth;
y_scale = (localVideo.clientHeight - y_offset * 2) / localVideo.videoHeight;
for (var i = 0; i < comp.length; i++) {
comp[i].x = comp[i].x * x_scale + x_offset;
comp[i].y = comp[i].y * y_scale + y_offset;
comp[i].width = comp[i].width * x_scale;
comp[i].height = comp[i].height * y_scale;
and then use the line
ctx.strokeRect(comp[i].x, comp[i].y, comp[i].width, comp[i].height);
replace all localvideo.clientwidth by App.video.width and ocalvideo.clientheight by App.video.height

Categories