我在使用构造函数生成drawimage时遇到问题。我需要生成这些行和行,所以我需要能够轻松地生成这些。到目前为止我无法解决这个问题。我现在收到的错误是Uncaught ReferenceError:requestAnimFrame未定义 有关如何解决此问题以使参数有效的任何想法?我需要将propertyName等于out,比如y1,y2,y2等等,因为这是我设置块的y的方式。
enemy.y = rand;
enemy.y2 = rand2;
enemy.y3 = rand3;
enemy.y4 = rand4;
enemy.y5 = rand5;
enemy.y6 = rand6;
enemy.y7 = rand7;
enemy.y8 = rand8;
enemy.y9 = rand9;
所以这里是敌人面前的代码.y1-y9' s。
var requestAnimFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimFrame
function drawPiece(x,y,letter){
this.x = x;
this.y = y;
this.letter = letter;
var propertyName = propertyName;
this.spawn = function(){
for(var i = 1; i <= 9; i++){
if(i > 1){
var propertyName = this.letter + i;
}
context.drawImage(imgs[0],enemy.x,enemy[propertyName], tileWidth, tileHeight);
}
}
enemy.propertyName = rand;
requestAnimFrame(drawPiece);
check();
}
var redblk = new drawPiece(900,rand,"y");
编辑:现在错误消失了。在构造函数中是否有足够的工作,看到这段代码?因为没有错误,但没有出现阻塞。
答案 0 :(得分:0)
不确定代码的完整语义,但我认为您需要更改:
...
requestAnimFrame(drawPiece);
...
var redblk = new drawPiece(900,rand,"y");
为此:
var redblk = new drawPiece(900,rand,"y");
requestAnimFrame(redblk.spawn);
但是,&#39; spawn&#39;的回调上下文可能是错的我在思考(必须经过验证,但我相信&#39;回调中的这个将指向窗口,而不是redblk)。
您可能想要更改:
function drawPiece(x,y,letter){
this.x = x;
this.y = y;
this.letter = letter;
var propertyName = propertyName;
this.spawn = function(){
for(var i = 1; i <= 9; i++){
if(i > 1){
var propertyName = this.letter + i;
}
context.drawImage(imgs[0],enemy.x,enemy[propertyName], tileWidth, tileHeight);
}
}
为此:
function drawPiece(x,y,letter){
this.x = x;
this.y = y;
this.letter = letter;
var propertyName = propertyName; //Is the RHS of this assignment properly defined?
var ThisClosure = this;
this.spawn = function(){
for(var i = 1; i <= 9; i++){
if(i > 1){
var propertyName = ThisClosure.letter + i;
}
context.drawImage(imgs[0],enemy.x,enemy[propertyName], tileWidth, tileHeight);
}
}
但是,您是否考虑过在其闭包中返回一个带参数的函数?
如果您之后不需要更改传递的参数,那么这样的事情会更优雅:
function drawPiece(x,y,letter){
//x, y and letter are defined in the closure of the returned function.
//judging by your use of it, propertyName is probably defined in the closure as well
return(function(){
for(var i = 1; i <= 9; i++){
if(i > 1){
var propertyName = letter + i;
}
context.drawImage(imgs[0],enemy.x,enemy[propertyName], tileWidth, tileHeight);
});
}
requestAnimFrame(drawPiece(900,rand,"y"));