[英]Javascript html5 canvas random switch statement images
我試圖隨機選擇一條語句,其中包含從Sprite表中的某個點繪制的值。 這是我當前的代碼。
this.asteroid = Math.floor(Math.random()*7+1);
switch(this.asteroid)
{
case 0:
this.srcX = 0;
this.srcY = 528;
this.width = 32;
this.height = 33;
break;
case 1:
this.srcX = 32;
this.srcY = 528;
this.width = 32;
this.height = 33;
break;
case 2:
this.srcX = 64;
this.srcY = 528;
this.width = 32;
this.height = 33;
break;
case 3:
this.srcX = 63;
this.srcY = 565;
this.width = 62;
this.height = 60;
break;
case 4:
this.srcX = 125;
this.srcY = 565;
this.width = 62;
this.height = 60;
break;
case 5:
this.srcX = 187;
this.srcY = 565;
this.width = 62;
this.height = 60;
break;
case 6:
this.srcX = 0;
this.srcY = 632;
this.width = 116;
this.height = 120;
break;
}
然后,我稍后將繪制它選擇的值。
問題是我大部分都在繪制它,但是同時只繪制一張空白圖像,我檢查了所有X和Y位置,它們在Sprite工作表中都正確且匹配。
下面是我用來繪制精靈的代碼:
this.drawX -= this.speed;
ctxEnemy.drawImage(imgSprite,
this.srcX+this.width,this.srcY,this.width,this.height,
this.drawX,this.drawY,this.width,this.height);
this.checkEscaped();
Math.floor(Math.random()*7+1)
值可以從1到7。刪除+1
。
我認為您的繪圖代碼可能有問題:
this.drawX -= this.speed;
ctxEnemy.drawImage(imgSprite,
this.srcX+this.width,this.srcY,this.width,this.height,
this.drawX,this.drawY,this.width,this.height);
this.checkEscaped();
在以下行中: this.srcX+this.width,this.srcY,this.width,this.height,
您正在將對象寬度添加到源位置。 我認為這可能會影響您的Sprite繪圖。 請參閱以下帶有參考注釋的示例:
// draw image to screen drawImage(imageObject,
// sourceX, sourceY, sourceWidth, sourceHeight,
// destinationX, destinationY, destinationWidth, destinationHeight)
ctx.drawImage(imageObject,
this.srcX, this.srcY, this.width, this.height,
this.drawX, this.drawY, this.width, this.height);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.