为什么.clearRect函数不能正常工作?

时间:2015-12-16 11:45:14

标签: javascript html5-canvas

所以我在javascript中制作这个太空入侵者游戏。我现在的问题是,当敌人左右移动时,他们不会清除rect,所以你可以看到他们的镜头如下所示: enter image description here

我只是想知道我能解决这个问题的方法。我很乐意,如果你能提供帮助,我的代码是:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Space Invaders</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <style>
  canvas{
    position: absolute;
    top:0px;
    left:0px;
    background: transparent;
  }
  #backgroundCanvas{
   background-color: black;
  }

  </style>
</head>
<body>

<canvas id="backgroundCanvas" width="550" height="600"></canvas>
<canvas id="playerCanvas" width="550" height="600"></canvas>
<canvas id="enemiesCanvas" width="550" height="600"></canvas>

   <script>
   (function(){
    $(document).ready(function(){
      var game = {};

      game.stars = [];
      game.width = 550;
      game.height = 600;
      game.images = [];

      game.doneImages = 0;
      game.requiredImages = 0;
      game.keys = [];
      game.enemies = [];

      game.count = 0;
      game.division = 48;
      game.left = false;
      game.enemySpeed = 3;

      game.contextBackground = document.getElementById("backgroundCanvas").getContext('2d');

      game.contextPlayer = document.getElementById("playerCanvas").getContext('2d');

      game.contextEnemies = document.getElementById("enemiesCanvas").getContext('2d');

      game.player = {
        x:  game.width / 2 -50,
        y:  game.height - 110,
        width:100,
        height:100,
        speed: 3,
        rendered: false
      }




      $(document).keydown(function(e){
        game.keys[e.keyCode ? e.keyCode : e.which] = true;

      })
      $(document).keyup(function(e){
       delete game.keys[e.keyCode ? e.keyCode : e.which];

      })

      /*
      up -38
      down-40
      left -37
      right-39
      w-87
      a-65
      s-83
      d-68
      space-32
    */

      function init(){
        for(i=0; i<600;i++){
          game.stars.push({
            x:Math.floor(Math.random()* game.width),
            y:Math.floor(Math.random()* game.height),
            size: Math.random()*5
          })
        }

        for(y=0;y<5;y++){
          for(x =0;x<5;x++){
             game.enemies.push({
              x: (x*70) + (70*x) + 10,
              y: (y*70) + (10*y) + 40,
              width:70,
              height: 70,
              image:1
             })
          }
        }


        loop();
      }
      function addStars(num){
          for(i=0; i<num;i++){
            game.stars.push({
              x:Math.floor(Math.random()* game.width),
              y:game.height+10,
              size: Math.random()*5
            })
          }

      }
      function update(){
         addStars(1);
         game.count++;
           for(i in game.stars){
            if(game.stars[i].y <= -5){
                game.stars.splice(i,1);
            }
            game.stars[i].y--;
           }

           if(game.keys[37] || game.keys[65]){
            if(game.player.x>=0){
              game.player.x-=game.player.speed;
              game.player.rendered = false;
            }

           }
          if(game.keys[39] || game.keys[68]){
              if(game.player.x<=500-50){
              game.player.x+=game.player.speed;
              game.player.rendered = false;
            }

           }
           if(game.count % game.division == 0){
            game.left = !game.left;
           }

           for(i in game.enemies){
              if(game.left){

                game.enemies[i].x-=game.enemySpeed;
              }else{
                game.enemies[i].x+=game.enemySpeed;
              }
            }
        }

      function render(){
         game.contextBackground.clearRect(0,0,game.width,game.height)
         game.contextBackground.fillStyle = "white";
         for(i in game.stars){
            var star = game.stars[i];
            game.contextBackground.fillRect(star.x,star.y,star.size,star.size);
         }
         if(!game.player.rendered){
       game.contextPlayer.clearRect(0, 0, game.width, game.height);
      game.contextPlayer.drawImage(game.images[0], game.player.x, game.player.y, game.player.width, game.player.height);
      game.player.rendered = true;
         }

         for(i in game.enemies){
          var enemy = game.enemies[i];
          game.contextEnemies.clearRect(enemy.x, enemy.y, enemy.width, enemy.height);
          game.contextEnemies.drawImage(game.images[enemy.image], enemy.x, enemy.y, enemy.width, enemy.height);
         }
      }

      function loop(){
          requestAnimFrame(function(){
            loop();
        });
        update();
        render();
      }

      function initImages(paths){
        game.requiredImages = paths.length;
          for(i in paths){
              var img = new Image;
              img.src = paths[i];
              game.images[i] = img;
              game.images[i].onload = function(){
                  game.doneImages++;
              }
          }
      }

      function checkImages(){

        if(game.doneImages>=game.requiredImages){
          init();
        }
        else{
          setTimeout(function(){
            checkImages();

          },1)
        }
      }
      game.contextBackground.font = "bold 50px monaco"
      game.contextBackground.fillStyle = "white";
      game.contextBackground.fillText("loading" , game.width/2-100 ,game.height/2-25)
     initImages(["player.gif", "enemy.png", "bullet.png","Image1.png","Image2.png"])
      checkImages();
});

  window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          window.oRequestAnimationFrame      ||
          window.msRequestAnimationFrame     ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
   })();
   })();

   </script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

现在,您使用此

清除contextEnemies
game.contextEnemies.clearRect(enemy.x, enemy.y, enemy.width, enemy.height);

这里的问题是你正在清除你将要绘制敌人的方块,而不是上次绘制的方格 。你需要跟踪你在之前的渲染(enemy.x)中吸引敌人的位置,并清除那部分。

要么向敌人物体添加enemy.lastx之类的东西,要跟踪它以前的位置。或者最简单的解决方案就是在使用contextEnemies时清除整个contextBackground

game.contextBackground.clearRect(0, 0, game.width, game.height);
game.contextEnemies.clearRect(0, 0, game.width, game.height);

希望有所帮助。干杯!