I am learning a bit about JavaScript animation. So far I have learned how to move an object back and forward on the screen. But what if I want the object to continuously move across the screen? I am looking for a way to loop it, so that the object slides in from the left of the screen, sliding across the whole screen, exiting to the right, and then slides in from the left again.
What should I do?
<div id="rect1" class="rect anim-frame"></div>
.rect {
position: absolute;
width: 150px;
height: 80px;
}
.timeout {
background: orange;
}
.anim-frame {
top: 100px;
background: green;
}
window.onload = () => {
startSetTimeoutAnimation();
startAnimFrameAnimation();
};
function startSetTimeoutAnimation() {
const refreshRate = 1000 / 60;
const maxXPosition = 1000;
let rect = document.getElementById('rect0');
let speedX = 1;
let positionX = 0;
window.setInterval(() => {
positionX = positionX + speedX;
if (positionX > maxXPosition || positionX < 0) {
speedX = speedX * (-1);
}
rect.style.left = positionX + 'px';
}, refreshRate);
}
function startAnimFrameAnimation() {
const refreshRate = 1000 / 60;
const maxXPosition = 1000;
let rect = document.getElementById('rect1');
let speedX = 1;
let positionX = 0;
function step() {
positionX = positionX + speedX;
if (positionX > maxXPosition || positionX < 0) {
speedX = speedX * (-1);
}
rect.style.left = positionX + 'px';
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}