-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.js
60 lines (49 loc) · 1.64 KB
/
run.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
window.addEventListener('load', () => {
const car = document.querySelector('.car');
const trackWidth = document.querySelector('.track-container').clientWidth;
const carWidth = car.clientWidth;
const distance = trackWidth - carWidth;
const duration = 3000; // Adjust the duration (in milliseconds) as desired
let animationId;
let isMoving = true;
let currentPosition = 0;
const startAnimation = () => {
isMoving = true;
const startTime = performance.now();
const moveCar = (timestamp) => {
const elapsedTime = timestamp - startTime;
const progress = elapsedTime / duration;
let newPosition = currentPosition + distance * progress;
// Check if the car has reached the end of the track
if (newPosition >= distance) {
// Calculate the remaining distance
const remainingDistance = newPosition - distance;
// Reset the car's position to the beginning of the track
newPosition = -carWidth + remainingDistance;
currentPosition = newPosition;
}
car.style.left = `${newPosition}px`;
if (progress < 1 && isMoving) {
animationId = requestAnimationFrame(moveCar);
} else {
currentPosition = newPosition;
}
};
requestAnimationFrame(moveCar);
};
const stopAnimation = () => {
isMoving = false;
cancelAnimationFrame(animationId);
};
document.addEventListener('keydown', (event) => {
if (event.key === 'c' || event.key === 'C') {
if (isMoving) {
stopAnimation();
} else {
startAnimation();
}
}
});
// Start the animation when the page loads
startAnimation();
});