-2

I am trying to make the image switch when I press the space bar. but.... when I do I get an error "ig is not defined" Im not sure why its happening any ideas? I should also note that I am using notepad its the free text editor on windows 10 im sure the same code works on mac and linux

Here is the code:

<!DOCTYPE html>
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas
var ctx
window.onload = function() {
    canvas = document.getElementById("gameCanvas")
    ctx = canvas.getContext("2d")
    ctx.fillStyle = "red"
    ctx.fillRect(0, 0, 50, 50)

    
    
}

    function draw() {
  ctx.clearRect(0, 0, 999, 999)
  Xpos = Xpos + Xspeed
  ctx.fillRect(Xpos, 0, 20, 20)
    
    var ig = new Image()

    ig.src = "alien2.png"
    
    


    var img = new Image();

    img.src = "scp.png";

    ctx.drawImage(img, Xpos, 145, 50, 50);
}



document.addEventListener("keydown", keyDown)
document.addEventListener("keyup", keyUp)



var Xspeed = 0
var Xpos = 10

setInterval(draw, 50)

function keyUp(evt) {
  if (evt.keyCode == 32) Xspeed = 0
    ctx.drawImage(ig, 100, 100)
}
function keyDown(evt) {
  if (evt.keyCode == 32) Xspeed = 2

    ctx.drawImage(ig, 100, 100)
    
}



</script>
</html>

DR_KIND
  • 1
  • 2
  • Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Sebastian Simon Jul 12 '21 at 22:38
  • You defined `ig` inside `draw` but you are using it outside of it... – CherryDT Jul 12 '21 at 22:50

1 Answers1

0

Move the functions inside the onload event listener so the functions can reference ctx and make ig a global variable:

var canvas
var ctx
window.onload = function() {
  canvas = document.getElementById("gameCanvas")
  ctx = canvas.getContext("2d")
  ctx.fillStyle = "red"
  ctx.fillRect(0, 0, 50, 50)

  function draw() {
    ctx.clearRect(0, 0, 999, 999)
    Xpos = Xpos + Xspeed
    ctx.fillRect(Xpos, 0, 20, 20)
    window.ig = new Image()
    ig.src = "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1";
    var img = new Image();
    img.src = "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1";
    ctx.drawImage(img, Xpos, 145, 50, 50);
  }

  document.addEventListener("keydown", keyDown)
  document.addEventListener("keyup", keyUp)

  var Xspeed = 0
  var Xpos = 10

  setInterval(draw, 50)

  function keyUp(evt) {
    if (evt.keyCode == 32) Xspeed = 0
    ctx.drawImage(ig, 100, 100)
  }

  function keyDown(evt) {
    if (evt.keyCode == 32) Xspeed = 2

    ctx.drawImage(ig, 100, 100)

  }


}
<!DOCTYPE html>
<html>

<body>
  <canvas id="gameCanvas" width="800" height="600"></canvas>
</body>

</html>
Spectric
  • 30,714
  • 6
  • 20
  • 43