使用两个画布制作跳跃效果越来越慢的游戏。

时间:2014-06-02 08:16:25

标签: javascript

我正在尝试创建一个包含两个画布的简单游戏。它们是相同的,并且一个放在另一个之上。第一个canvas1用于自动滚动背景图像。第二个Canvas2用于按下向前箭头键时将跳到某个高度的对象。用于使对象跳转的canvas2放置在canvas1的顶部,用于自动滚动图像。在单个画布上单独使用时,用于使跳转的代码工作正常。但是在这个游戏中它更慢,随着时间的推移,它变得越来越慢。问题是什么以及如何解决?

小提琴:

GAME FIDDLE

background image which scrolls

object which jumps

jump code works normal when used seperately

CSS:

<head>
<style>

*{margin:0px;padding:0px;}
body{position:relative;}
#mydiv{
width:100%;
height:100%;
background-color:black;
}
#mycanvas1{

margin-top:50px;
margin-left:250px;
border:1px solid white;

}
#mycanvas2{
position:absolute;
top:50px;
left:250px;
border:1px solid white;


}

</style>
</head>

HTML:

<div id="mydiv">
<canvas id="mycanvas1"></canvas>
<canvas id="mycanvas2"></canvas>
</div>

SCRIPT: (用于滚动)

var canvas1=document.getElementById("mycanvas1");
canvas1.width=500;
canvas1.height=500;
var ctxbg=canvas1.getContext('2d');
var canvas2=document.getElementById("mycanvas2");
canvas2.width=500;
canvas2.height=500;
ctxbox=canvas2.getContext('2d');

var velocity=50;
var bgImage=new Image();
bgImage.addEventListener('load',drawImage,false);
bgImage.src="images/bg.png";
function drawImage(time){

        var framegap=time-lastRepaintTime;
        lastRepaintTime=time;
        var translateX=velocity*(framegap/1000);
        ctxbg.clearRect(0,0,canvas1.width,canvas1.height);
        var pattern=ctxbg.createPattern(bgImage,"repeat-x");
        ctxbg.fillStyle=pattern;
        ctxbg.rect(-translateX,0,bgImage.width,bgImage.height);
       ctxbg.fill();
          ctxbg.translate(translateX,0);

    requestAnimationFrame(drawImage);


}
var lastRepaintTime=window.performance.now();
requestAnimationFrame(drawImage);

(FOR JUMPING)

var gravity=0.1;
var keypressed=false;
var boxImage=new Image();

boxImage.src="images/grass.jpg";
function box(x,y){
   this.x=x;
   this.y=y;
   this.speed=0;
   this.image=boxImage;
   }
   box.prototype.hop=function(){
          if(this.y+this.image.height>canvas2.height){
              this.y=500-36;
              this.speed=0;
              }else{

          this.speed=this.speed+gravity;
          this.y+=this.speed;
          }
   }
  box.prototype.draw=function (){

   ctxbox.drawImage(this.image,this.x,this.y);

}  
 var greenBox=new box(10,450);  
requestAnimationFrame(function loop(){

  ctxbox.clearRect(0,0,canvas2.width,canvas2.height);
  greenBox.draw();
  if(keypressed==true){
  greenBox.speed=-5
   keypressed=false;

  }
greenBox.hop();

requestAnimationFrame(loop);
});

document.addEventListener('keydown',function(e){

       if(e.keyCode==38){

      keypressed=true;



       }



},false);

0 个答案:

没有答案