【发布时间】:2016-03-02 05:11:49
【问题描述】:
我正在使用 javascript 开发视频游戏,但我无法将我的函数打印到画布上。我没有收到任何错误,所以我无法确定为什么会这样。这个函数应该接受图像的名称以连接到存储在单独图像文件中的 .png 上,x 和 y 位置,图像的高度和宽度,以及用于打印的画布和上下文。下面是我的代码。
function loadCanvas(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//Sprite function
var sprite = function(imageName, imageX, imageY, imageHeight, imageWidth, context, canvas){
this.imageName = imageName;
this.imageX = imageX;
this.imageY = imageY;
this.imageHeight = imageHeight;
this.imageWidth = imageWidth;
this.canvas = canvas;
this.context = context;
}
//Sprite draw function
sprite.prototype.draw = function(){
var character = new Image();
character.src = "../Images/" + this.imageName + ".png";
var cont = this.context;
character.onload = function(){
cont.drawImage(character, this.imageX, this.imageY, this.imageWidth, this.imageHeight);
}
}
sprite.prototype.getHeight = function(){
return this.imageHeight;
}
sprite.prototype.getWidth = function(){
return this.imageWidth;
}
sprite.prototype.getX = function(){
return this.imageX;
}
sprite.prototype.getY = function(){
return this.imageY;
}
sprite.prototype.moveUpX = function(e){
this.imageX = (this.imageX + e);
}
sprite.prototype.moveUpY = function(e){
this.imageY = (this.imageY + e);
}
sprite.prototype.moveBackX = function(e){
this.imageX = (this.imageX - e);
}
sprite.prototype.moveBackY = function(e){
this.imageY = (this.imageY - e);
}
sprite.prototype.changeImage = function(e){
this.imageName = e;
}
sprite.prototype.getImage = function(){
return this.imageName;
}
sprite.prototype.changeX = function(e){
this.imageX = e;
}
sprite.prototype.changeY = function(e){
this.imageY = e;
}
sprite.prototype.getContext = function(){
return this.context;
}
var sprites = [];
sprites[1]= new sprite("RoomOne", 0, 0, 800, 400, context, canvas);
sprites[1].draw();
}
这是我的 HTML,上面的所有代码都包含在“loadCanvas”函数中:
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src = 'game.js'></script>
</head>
<body onload = "loadCanvas()">
<canvas id='canvas' width="800" height="400" style="border:0px solid #c3c3c3;">
This is not supported in your browser.
</canvas>
</body>
</html>
【问题讨论】:
-
你也能发布你的html吗?
-
我刚刚更新了它,希望对您有所帮助。谢谢。
标签: javascript function canvas