canvas sprite动画 简单封装

 1 function SpritCtx(img, size, pos, turnTime, totalCount, ctx) {
 2     size = size || {};
 3     pos = pos || {};
 4     //img
 5     this.img = img;
 6     //size
 7     this.width = size.width || 5;
 8     this.height = size.height || 5;
 9     //pos
10     this.left = pos.left || 0; //画布上的位置left
11     this.top = pos.top || 0; //画布上的位置top
12     //初始化cellNum,count,cell,row
13     this.cellNum = 1;
14     var that = this;
15     this.img.onload = function() {
16         that.cellNum = Math.floor(that.img.width / that.width); //每行的个数            
17     }
18     this.count = 0; //显示第几个
19     this.cell = 0;
20     this.row = 0;
21     //定时器时间
22     this.turnTime = turnTime || 90;
23     //图片数量
24     this.totalCount = totalCount;
25     //canvas
26     this.ctx = ctx;
27     //定时器
28     this.xTimer = null;
29 }
30 
31 SpritCtx.prototype.draw = function() {
32     this.ctx.drawImage(
33         this.img,
34         this.width * this.cell,
35         this.height * this.row,
36         this.width,
37         this.height,
38         this.left,
39         this.top,
40         this.width,
41         this.height
42     );
43     return this;
44 };
45 
46 SpritCtx.prototype.start = function() {
47     var that = this;
48     clearInterval(this.xTimer);
49     this.xTimer = setInterval(function () {
50         that.timerFn();
51     }, this.turnTime);
52     return this;
53 };
54 
55 SpritCtx.prototype.stop = function() {
56     clearInterval(this.xTimer);
57     return this;
58 };
59 
60 SpritCtx.prototype.timerFn = function() {
61     this.count++;
62     this.count %= this.totalCount;
63     this.row = Math.floor(this.count / this.cellNum); //第几行
64     this.cell = this.count - this.row * this.cellNum; //第几列
65     return this;
66 };
67 
68 SpritCtx.prototype.turnPos = function(left, top) {
69     this.left = left || 0;
70     this.top = top || 0;
71     return this;
72 };

 

posted @ 2016-10-25 16:36  forever希望  阅读(595)  评论(0编辑  收藏  举报