我正在尝试学习和运行这个 JavaScript 脚本,以便创建基于 HTML5 的游戏。我正在努力找出这段代码中的错误。它不工作。Chrome 的开发工具说我没有明确定义x
它何时显示var x = 0;"=
。这是代码,有人可以帮我找到错误并建议我如何解决它吗?这是代码:
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();