我正在使用Javascript创建视频游戏,而且我的知识非常基础。我正在尝试创建一个函数,用于创建所有精灵以及将它们打印到画布上,但是当我尝试打印它们时,没有任何作用。我不完全确定问题是什么,或者我完全错了。以下是我目前的代码。
//Gets canvas and context
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//Creates all attributes of sprite
function sprite(imageName, imageX, imageY, imageHeight, imageWidth){
this.imageName = imageName;
this.imageX = imageX;
this.imageY = imageY;
this.imageHeight = imageHeight;
this.imageWidth = imageWidth;
this.draw = function(){
character = new Image();
character.src = "../Images/" + this.imageName + ".png";
character.onload = function(){
context.drawImage(character, this.imageX, this.imageY, this.imageWidth, this.imageHeight);
}
};
this.getHeight = function(){
return this.imageHeight;
};
this.getWidth = function(){
return this.imageWidth;
};
this.getX = function(){
return this.imageX;
};
this.getY = function(){
return this.imageY;
};
this.moveUpX = function(e){
this.imageX = (this.imageX + e);
};
this.moveUpY = function(f){
this.imageY = (this.imageY + e);
};
this.moveBackX = function(e){
this.imageX = (this.imageX - e);
};
this.moveBackY = function(f){
this.imageY = (this.imageY - e);
};
this.changeImage = function(a){
this.imageName = a;
};
this.getImage = function(){
return imageName;
};
this.changeX = function(b){
this.imageX = b;
};
this.changeY = function(c){
this.imageY = c;
};
}
//Creates Sprite
sprites[0] = new sprite('mySprite', 0, 0, 36, 51);
sprites[0].draw();
答案 0 :(得分:0)
您的sprites
var未定义。您需要先定义
var sprites = []; // add this line
sprites[0] = new sprite('mySprite', 0, 0, 36, 51);
sprites[0].draw();