0
点赞
收藏
分享

微信扫一扫

精灵表绘制器29

SpriteSheetPainter = function (cells) {
   this.cells = cells;
};

SpriteSheetPainter.prototype = {
   cells: [],//数组索引,记录精灵表中每个单元的信息
   cellIndex: 0,

   advance: function () {//把索引值加1,以便在下一帧画第二个单元格的信息
      if (this.cellIndex == this.cells.length-1) {
         this.cellIndex = 0;
      }
      else {
         this.cellIndex++;
      }
   },
   
   paint: function (sprite, context) {
      var cell = this.cells[this.cellIndex];
      //spritesheet这个对象是在外面定义的
      context.drawImage(spritesheet, cell.left, cell.top,
                                     cell.width, cell.height,
                                     sprite.left, sprite.top,
                                     cell.width, cell.height);
   }
};
//........................................................
var spritesheet = new Image();
var runnerCells = [
      { left: 0,   top: 0, width: 47, height: 64 },
      { left: 55,  top: 0, width: 44, height: 64 },
      { left: 107, top: 0, width: 39, height: 64 },
      { left: 150, top: 0, width: 46, height: 64 },
      { left: 208, top: 0, width: 49, height: 64 },
      { left: 265, top: 0, width: 46, height: 64 },
      { left: 320, top: 0, width: 42, height: 64 },
      { left: 380, top: 0, width: 35, height: 64 },
      { left: 425, top: 0, width: 35, height: 64 },
    ],
    sprite = new Sprite('runner', new SpriteSheetPainter(runnerCells));
    
function animate(time) {
    context.clearRect(0, 0, canvas.width, canvas.height);//精灵会原地跑动
    sprite.paint(context);
    sprite.painter.advance();/*************************/

    window.requestNextAnimationFrame(animate);
   }
}

举报

相关推荐

0 条评论