Canvas and JavaScript – Flowing word from right to left while waiting for keypress input

  canvas, javascript

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>

Source: Ask Javascript Questions

LEAVE A COMMENT