I am trying to learn and run this JavaScript script so that I can create an HTML5 based game. I'm struggling to figure out the error in this code. It is not working. Chrome's Dev tools say that I'm not defining x when very clearly it says var x = 0;"=. Here's the code, could someone help me find the error and suggest how I might fix it? Here's the code:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var player;
var playerImage = new Image();
var playerImage = 'http://jonah.pro/Block_Die/dev/src/player.gif';
var PlayerX = canvas.width / 2;
var PlayerY = canvas.width / 2;
var x = 0;
var y = 0;
function init() {
player.x = PlayerX + x;
player.y = PlayerY + y;
ctx.drawImage(playerImage, player.x, player.y);
};
document.onkeydown = function(e) {
if ( e.keyCode === 87 ) {
y -= 2;
alert("up!");
} //up
if ( e.keyCode === 83 ) {
y += 2;
alert("down!");
}//down
if ( e.keyCode === 65 ) {
x -= 2;
alert("left!");
}//left
if ( e.keyCode === 68 ) {
x += 2;
alert("right!");
}//right
}
init();