I wanna repeat function infinite but i couldn't - javascript

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/

Related

Please i need help: Trying to have my animation move from initial coordinates to new inputted coordinates using JavaScript

I have Layout with a machine, i intend to have this machine (purple animation) move from point A to point B based on input cordinate x and cordinate Y. I followed some online tutorials but still not been able to get it. The animation currently moves manually with arrow keys but i intend to have it move automatically. The aim is to have the animation move at a slow frame pace to the inserted coordinates. Any help will be appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Farm Harvest </title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="grid"></div>
<input type="number" id = 'cords1' placeholder="X-Cordinates">
<input type="number" id = 'cords2' placeholder="Y-Cordinates">
<button id = "mybtn" onclick="myCords();">Get Value</button>
<script src="app.js"></script>
</body>
</html>
CSS:
.grid {
position: absolute;
width: 560px;
height: 300px;
border: solid 1px black;
margin-top: 100px;
}
.user {
position: absolute;
width: 30px;
height: 20px;
background-color: blueviolet;
}
.block {
position: absolute;
width: 100px;
height: 20px;
background-color: blue;
}
JS:
const grid = document.querySelector('.grid')
const value1 = document.getElementById('cord1')
const value2 = document.getElementById('cord2')
const blockWidth = 100
const blockHeight = 20
const boardWidth = 560
const boardHeight = 300
var mouseX, mouseY;
var stepWidthFactor = 200;
const userStart = [10, 270]
let currentPosition = userStarnst userStart1 = [10, 270]
let currentPosition1 = userStart1
const user1 = [10, 270]
let currentPosition2 = user1
//my block
class Block {
constructor(xAxis, yAxis) {
this.bottomLeft = [xAxis, yAxis]
this.bottomRight = [xAxis + blockWidth, yAxis]
this.topRight = [xAxis + blockWidth, yAxis + blockHeight]
this.topLeft = [xAxis, yAxis + blockHeight]
}
}
class moveblock{
constructor(xAxis,yAxis){
this.xAxis = inputval0;
this.yAxis = inputval1;
let currentPosition3 = user2;
}
}
//all my blocks
const blocks = [
new Block(120, 210),
new Block(230, 210),
new Block(340, 210),
new Block(120, 140),
new Block(230, 140),
new Block(340, 140),
new Block(120, 70),
new Block(230, 70),
new Block(340, 70),
]
//draw my blocks
function addBlocks() {
for (let i = 0; i < blocks.length; i++) {
const block = document.createElement('div')
block.classList.add('block')
block.style.left = blocks[i].bottomLeft[0] + 'px'
block.style.bottom = blocks[i].bottomLeft[1] + 'px'
grid.appendChild(block)
console.log(blocks[i].bottomLeft)
}
}
addBlocks()
//add user
const user = document.createElement('div')
user.classList.add('user')
grid.appendChild(user)
drawUser()
//move user
function moveUser(e) {
switch (e.key) {
case 'ArrowLeft':
if (currentPosition[0] > 0) {
currentPosition[0] -= 10
console.log(currentPosition[0] > 0)
drawUser()
}
break
case 'ArrowRight':
if (currentPosition[0] < (boardWidth - blockWidth)) {
currentPosition[0] += 10
console.log(currentPosition[0])
drawUser()
}
break
case 'ArrowDown':
if (currentPosition1[0] < (boardHeight - blockHeight)) {
currentPosition1[0] += 10
console.log(currentPosition1[0]>0)
drawUser()
}
break
case 'ArrowUp':
if (currentPosition1[0] > 0) {
currentPosition1[0] -= 10
console.log(currentPosition1[0])
drawUser()
}
break
}
}
document.addEventListener('keydown', moveUser)
//draw User
function drawUser() {
user.style.top = currentPosition1 [0] + 'px'
user.style.left = currentPosition[0] + 'px'
user.style.bottom = currentPosition[0] + 'px'
user.style.right = currentPosition[0] + 'px'
}
function myCords(){
const user2 = [inputval0,inputval1]
let currentPosition3 = user2;
var inputval0 = document.getElementById('cords1').value;
var inputval1 = document.getElementById('cords2').value;
if(inputval0 < boardHeight && inputval1 < boardWidth && inputval0 != 0 && inputval1 != 0){
alert("good cords " + "X: "+ inputval0 + " " +"Y: " +inputval1)
}
else{
alert("wrong cordinates")
}
}document.addEventListener('onclick',myCords)
function drawnewUser(){
user.style.left = currentPosition + 'px';
user.style.top = currentPosition + 'px'
user.style.bottom = currentPosition + 'px'
user.style.right = currentPosition + 'px'
}

Random movement of circles created by the script

I have a function that craeates divs with a circle.
Now they are all created and appear at the beginning of the page and go further in order.
Next, I need each circle to appear in a random place. I did this.
Now I need all of them to move randomly across the entire page, I have difficulties with this.
Here is an example of how everything works for one element that is already on the page.
https://jsfiddle.net/quej8wko/
But when I add this code, all my created circles don't move.
I get an error:
"message": "Uncaught TypeError: Cannot set properties of null (setting 'willChange')",
This is probably due to the fact that initially there are no circles on the page. How can I connect the code so that all created circles move?
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
I have modified the snippet which works as you expected.
There was a mistake where you were initializing and creating the object instance only once and none of the div elements that you created inside the setInterval function never got Instantiated.
I think you are just starting out with JavaScript with this sample project.
Below are few suggestions:
Learn to debug the code. You should be using dev tools by making use of debugger statement where it takes you to the source code to analyze the variable scope and stack during the runtime. console.log also helps in few situations.
I could see a lot of confusing naming convention (You have named the create div parameter as id but creating a div class using that id)
Try using ES6 features (class syntax is really good when writing OOP in JS although it's just a syntactic sugar for prototype)
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createAndInitializeDivObject(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
var x = new RandomObjectMover(document.querySelector(`.${id}`), window);
x.start();
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createAndInitializeDivObject(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
width: 35px;
height: 35px;
border-radius: 35px;
background-color: #ffffff;
border: 3px solid purple;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="circle"></div>
<script src="app.js"></script>
</body>
</html>

make divs with an resizeable width on both sides

I have some trouble making my divs resizeable.
Im trying to make a time scheduler, but the divs should be resizeable and change width based on the resized one.
This is what I currently have now.
var stepsize = 5;
var min = 0;
var max = 1440;
var stepwidth = 100 / max;
let original_width = 0;
let original_height = 0;
let original_x = 0;
let original_y = 0;
let original_mouse_x = 0;
let original_mouse_y = 0;
console.log(stepwidth);
var timeblocks = {0: [50, 100, "red"], 1: [100, 200, "blue"], 2: [200, 400, "red"]};
calcwidth(timeblocks);
function calcwidth(timeblocks){
const values = Object.values(timeblocks)
var container = document.getElementById("container");
var int = 0;
var startmargin = 0;
for (const arrayv of values) {
console.log(arrayv);
var start = 0;
var end = 0;
if(int == 0){
start = stepwidth * arrayv[0];
console.log(start);
end = stepwidth * arrayv[1] - start;
startmargin = startmargin + (start + end);
}
else{
start = startmargin;
end = stepwidth * arrayv[1] - start;
startmargin = startmargin + (end);
}
console.log(startmargin);
var timeblock = document.createElement('div');
timeblock.className = "timeblock";
timeblock.style.background = arrayv[2];
timeblock.style.marginLeft = start + "%";
timeblock.style.width = end + "%";
var moverleft = document.createElement('div');
moverleft.style.width = "5px";
moverleft.style.height = "50px";
moverleft.style.background = "black";
moverleft.style.marginLeft = "0px";
moverleft.style.position = "absolute";
moverleft.style.opacity = "0.4";
moverleft.addEventListener('mousedown', function(e) {
e.preventDefault()
original_width = timeblock.style.marginLeft;
original_x = timeblock.getBoundingClientRect().left;
original_mouse_x = e.pageX;
console.log(original_width);
moverleft.addEventListener('mousemove', resize);
moverleft.addEventListener('mouseup', stopResize);
});
var moverright = document.createElement('div');
moverright.style.width = "5px";
moverright.style.height = "50px";
moverright.style.background = "black";
moverright.style.right = "0px";
moverright.style.position = "absolute";
moverright.style.opacity = "0.4";
timeblock.appendChild(moverleft);
timeblock.appendChild(moverright);
container.appendChild(timeblock);
int++;
}
}
function resize(e) {
const width = original_width - (e.pageX - original_mouse_x)
console.log(e.target.parentElement);
e.target.parentElement.style.marginLeft = width + 'px'
}
function stopResize() {
window.removeEventListener('mousemove', resize)
}
.timeblock{
position: absolute;
height: 50px;
}
.timeblock:hover{
background: green !important;
}
#container{
width: 100%;
height: 50px;
border: 1px solid black;
}
<div class="col-xs-12">
<div class="col-xs-12" id="container">
</div>
</div>
It seems the divs don't get resized, what am I doing wrong?
I want to make all divs resizeable by their handlers and move others based on the resize.
Does someone have an example what I can use, cuz I have no clue on how to do this.
Please help me!

checkCollision function is not working in Array.forEach (check elements collision)

why my checkCollision function is not working in foreach loop ? I want to check whether obs (obstacle) is hits/overlaps on collector (gray object). I am checking every 1 millisecond using setInterval checkCollision function. Basically I am trying to build a simple car game. please help me and thank you in advance
let body = document.body[0];
let container = document.querySelector(".container");
let allObstacles = [];
let colors = ["green", "green", "red"];
let collector = document.getElementById("collector");
class Obstacle {
constructor(yPos) {
this.yPos = -50;
}
randomnum() {
let randX = Math.floor(Math.random() * (container.clientWidth - 50));
return randX;
}
createObstacle() {
let obstacle = document.createElement("div");
obstacle.classList.add("obstacle");
let bgColor = colors[Math.floor(Math.random() * colors.length)];
obstacle.style.width = "50px";
obstacle.style.height = "50px";
obstacle.style.position = "absolute";
obstacle.style.left = this.randomnum() + "px";
obstacle.style.top = this.yPos + "px";
obstacle.style.backgroundColor = bgColor;
obstacle.dataset.behave = bgColor;
container.appendChild(obstacle);
return obstacle;
}
element = this.createObstacle();
updatePosition() {
this.yPos += 2;
this.element.style.top = this.yPos + "px";
}
kill() {
this.element.remove();
}
}
let dropObs = setInterval(function() {
allObstacles.forEach(function(obs) {
obs.updatePosition();
});
allObstacles.forEach(function(obs) {
// why checkCollision function is not working?
if (checkCollision(obs, collector)) {
console.log("hit");
}
if (obs.yPos > container.clientHeight) {
obs.kill();
}
});
}, 10);
let generateObs = setInterval(function() {
let obs = new Obstacle();
allObstacles.push(obs);
}, 2000);
function checkCollision(obj1, obj2) {
var obj1Y = obj1.offsetTop;
var obj2Y = obj2.offsetTop;
var obj1X = obj1.offsetLeft;
var obj2X = obj2.offsetLeft;
if (
obj2Y + 100 >= obj1Y &&
obj2Y <= obj1Y + 100 &&
obj2X + 100 >= obj1X &&
obj2X <= obj1X + 100
) {
return 1;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: 0;
}
html,
body {
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 100%;
height: 100%;
}
#collector {
width: 50px;
height: 100px;
background: gray;
position: absolute;
top: calc(100vh - 100px);
left: 50%;
margin-left: -25px;
}
<div class="container">
<div id="collector"></div>
</div>
The first thing you should not use setInterval for this type of animation. Use requestAnimationFrame
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
obj1X,obj1Y comming undefined.

JavaScript : animation for a div

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

Categories