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>