'Why my requestAnimationFrame is not working?
I am trying to make the car move using JavaScript by using requestAnimationFrame. I have a car on the screen but the car is not moving; for some reason, my animation is not working.
const canvas = document.getElementById("myCanvas")
canvas.height = window.innerHeight
canvas.width = 200
//Draw the car on canvas
const ctx = canvas.getContext('2d') // use 2d canvas context
const car = new Car(100, 100, 30, 50)
// car.draw(ctx) // draw the car using the context
//move the car
animate();
function animate() {
car.update();
car.draw(ctx);
requestAnimationFrame(animate); // calls the animate function again and again as many times as we want
//give illusion of the movement that we want
}
body {
margin: 0;
background: darkgray;
overflow: hidden;
text-align: center;
}
#myCanvas {
background: lightgray;
}
<canvas id="myCanvas"></canvas>
<script>
class Controls {
constructor() {
this.forward = false
this.left = false
this.right = false
this.reverse = false
this.#addKeyboardListeners(); //# is used here because this is a private method, you can't access this from outside of the controls class
}
#addKeyboardListeners() {
document.onkeydown = (event) => {
switch (event.key) {
case "ArrowLeft":
this.left = true
break;
case "ArrowRight":
this.right = true
break
case "ArrowUp":
this.forward = true
break
case "ArrowDown":
this.reverse = true
break
}
// console.table(this)
}
document.onkeyup = (event) => {
switch (event.key) {
case "ArrowLeft":
this.left = false
break;
case "ArrowRight":
this.right = false
break
case "ArrowUp":
this.forward = false
break
case "ArrowDown":
this.reverse = false
break
}
// console.table(this)
}
}
}
</script>
<script>
class Car {
constructor(x, y, width, height) {
this.x = x
this.y = y
this.width = width
this.height = height
this.controls = new Controls();
}
//update the position of the car according to the key pressed
update() {
if (this.controls.forward) {
console.log("going up");
this.y -= 2
}
if (this.controls.reverse) {
this.y += 2
}
}
//draw a static car
draw(ctx) {
ctx.beginPath();
ctx.rect(
this.x - this.width / 2,
this.y = this.height / 2,
this.width,
this.height
);
ctx.fill();
}
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
