如果它到达底部,如何暂停我的循环? Window.requestanimationframe - Javascript / html5画布

时间:2017-01-10 05:23:01

标签: javascript html5 canvas

如果你想运行它,这是我的完整代码。 https://repl.it/FEl8/0 这里只是javascript:

    window.onload   =   function(){
    var canvas = document.getElementById('mycanvas');
    var ctx = canvas.getContext('2d');
    var warrior = document.getElementById('warrior');
    var enemyxpos = 100;
    var enemyypos = 75;
    canvas.width = window.screen.width;
    canvas.height = window.screen.height;
    var image = new Image();
    image.src = "sprite_guy_warrior-1.png";

     window.requestAnimationFrame(function loop(){
          enemyypos +=1;
          ctx.clearRect(enemyxpos,enemyypos,90,90);
          ctx.drawImage(image,enemyxpos,enemyypos,90,90);
         window.requestAnimationFrame(loop);
      });
 };

我希望在它到达画布底部时停止'图像'。谁能告诉我怎么做。

2 个答案:

答案 0 :(得分:0)

获取height of the canvas并检查y的值。

   window.onload   =   function(){
    var canvas = document.getElementById('mycanvas');
     var cheight=canvas.height;
    var ctx = canvas.getContext('2d');
    var warrior = document.getElementById('warrior');
    var enemyxpos = 100;
    var enemyypos = 75;
    var flag=90;//height of the image
    canvas.width = window.screen.width;
    canvas.height = window.screen.height;
    var image = new Image();
    image.src = "http://cliparts.co/cliparts/nrc/L6p/nrcL6pi84.png";
     window.requestAnimationFrame(function loop(){
          enemyypos +=1;
          ctx.clearRect(enemyxpos,enemyypos,90,90);
          ctx.drawImage(image,enemyxpos,enemyypos,90,90);
          if(cheight+flag >= enemyypos){ //here...........
             window.requestAnimationFrame(loop);
          }else{
               ctx.clearRect(0, 0, canvas.width, canvas.height);//clear the canvas ans start again.
             enemyypos = 75; 
          window.requestAnimationFrame(loop); }
      });

};

DEOM HERE

答案 1 :(得分:0)

只需在循环中使用此条件:

if (enemyypos <= canvas.height - 90){
    window.requestAnimationFrame(loop);
} 

这是repl