I’m new and I am trying to write my first program. In this snippet I try to flow a word from right to left and on the left move a bar to the right and when they collide a life will be taken. I also have a keypress event that strips the word of its corresponding character. The problem is that the animation goes too fast. There is no time to listen for input and give score. I have tried with setTimeout and SetInterval but they dont work. Thanks a bunch!
JavaScript
x
27
27
1
let positionBar = 10;
2
let positionWord = 600;
3
let positionWordHeight = 90;
4
const word = "Word";
5
let canvas = document.getElementById("canvas");
6
let context = canvas.getContext("2d");
7
8
function clrScr() {
9
context.clearRect(0, 0, canvas.width, canvas.height);
10
}
11
12
function getRandom(min, max) {
13
return Math.trunc(Math.random() * (max - min) + min);
14
}
15
16
while (positionBar < 600 && positionBar < positionWord) {
17
clrScr();
18
positionBar += 0.01;
19
positionWord -= 0.07;
20
21
context.beginPath();
22
context.rect(positionBar, 10, 10, 200, "black");
23
context.fill();
24
25
context.font = "30px Arial";
26
context.fillText(word, positionWord, positionWordHeight);
27
}
JavaScript
1
1
1
<canvas id="canvas" height="600" width="800"></canvas>
Advertisement
Answer
You can use a callback like setInterval()
or requestanimationframe()
to draw each frame sequentially. Here’s a simple example that only modifies your code slightly. You should research the topic to understand more fully.
JavaScript
1
36
36
1
let positionBar = 10;
2
let positionWord = 600;
3
let positionWordHeight = 90;
4
const word = "Word";
5
let canvas = document.getElementById("canvas");
6
let context = canvas.getContext("2d");
7
8
function clrScr() {
9
context.clearRect(0, 0, canvas.width, canvas.height);
10
}
11
12
function getRandom(min, max) {
13
return Math.trunc(Math.random() * (max - min) + min);
14
}
15
16
function draw(elapsed)
17
{
18
if (positionBar < 600 && positionBar < positionWord) {
19
clrScr();
20
positionBar += 0.01;
21
positionWord -= 0.07;
22
23
context.beginPath();
24
context.rect(positionBar, 10, 10, 200, "black");
25
context.fill();
26
27
context.font = "30px Arial";
28
context.fillText(word, positionWord, positionWordHeight);
29
30
// Call again for next frame
31
window.requestAnimationFrame(draw);
32
}
33
}
34
35
// Start animation
36
window.requestAnimationFrame(draw);
JavaScript
1
1
1
<canvas id="canvas" height="600" width="800"></canvas>