Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72358

setTimeout to delay change on canvas

$
0
0

When the right button is held down the herocolor changes to green (this already works), but I added a setTimeout so that after 1 second (while the button is still being held down) herocolor will become blue (this does not work). When the button is released it does turn back to red as expected.

My goal is to make the color toggle back and forth between green and blue every 1 second.

The alert properly delays and properly updates herocolor to blue but the square does not turn blue. I am utterly mystified why this isn't working.

loop = function() {

  var herocolor = "#ff0000";
  if (controller.right == true){
     herocolor = "#00ff00";
    setTimeout(function(){
      herocolor = "#0000ff";
      alert(herocolor);
    }, 1000);
  }

  context.fillStyle = "#202020";
  context.fillRect(0, 0, 800, 400);
  context.fillStyle = herocolor;
  context.beginPath();
  context.rect(hero.x, hero.y, hero.width, hero.height);
  context.fill();

  window.requestAnimationFrame(loop);
};

COMPLETE CODE

<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width=device-width">
<style>
* {
  box-sizing:border-box;
  margin:0;
  padding:0;
}
html, body {
  height:100%;
  width:100%;
}
body {
  align-content:space-around;
  background-color:#202830;
  color:#ffffff;
  display:grid;
  justify-content:center;
}
canvas {
  background-color:#ffffff;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
var context, controller, hero, loop;
context = document.querySelector("canvas").getContext("2d");
context.canvas.height = 400;
context.canvas.width = 800;
hero = {
  height:40,
  width:40,
  x:144,
  y:140,
};
controller = {
  right:false,
  up:false,
  keyListener:function(event) {
    var key_state = (event.type == "keydown")?true:false;
    switch(event.keyCode) {
      case 39:
        controller.right = key_state;
      break;
    }
  }
};
loop = function() {

  var herocolor = "#ff0000";
  if (controller.right == true){
     herocolor = "#00ff00";
    setTimeout(function(){
      herocolor = "#0000ff";
      alert(herocolor);
    }, 1000);
  }

  context.fillStyle = "#202020";
  context.fillRect(0, 0, 800, 400);
  context.fillStyle = herocolor;
  context.beginPath();
  context.rect(hero.x, hero.y, hero.width, hero.height);
  context.fill();

  window.requestAnimationFrame(loop);
};
window.addEventListener("keydown", controller.keyListener)
window.addEventListener("keyup", controller.keyListener);
window.requestAnimationFrame(loop);
</script>
</body>

Viewing all articles
Browse latest Browse all 72358

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>