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!
let positionBar = 10;
let positionWord = 600;
let positionWordHeight = 90;
const word = "Word";
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
function clrScr() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function getRandom(min, max) {
return Math.trunc(Math.random() * (max - min) + min);
}
while (positionBar < 600 && positionBar < positionWord) {
clrScr();
positionBar += 0.01;
positionWord -= 0.07;
context.beginPath();
context.rect(positionBar, 10, 10, 200, "black");
context.fill();
context.font = "30px Arial";
context.fillText(word, positionWord, positionWordHeight);
}<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.
let positionBar = 10;
let positionWord = 600;
let positionWordHeight = 90;
const word = "Word";
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
function clrScr() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function getRandom(min, max) {
return Math.trunc(Math.random() * (max - min) + min);
}
function draw(elapsed)
{
if (positionBar < 600 && positionBar < positionWord) {
clrScr();
positionBar += 0.01;
positionWord -= 0.07;
context.beginPath();
context.rect(positionBar, 10, 10, 200, "black");
context.fill();
context.font = "30px Arial";
context.fillText(word, positionWord, positionWordHeight);
// Call again for next frame
window.requestAnimationFrame(draw);
}
}
// Start animation
window.requestAnimationFrame(draw);<canvas id="canvas" height="600" width="800"></canvas>