跳到主要内容

进阶用法

多张图片组合

  • 在定义一个动画时,我们可以使用多张图片组合成一个动画,这样可以减少图片的大小,提高加载速度。

  • 此外,如果图片过大,会造成动画的卡顿,所以我们可以将图片分割成多张,然后组合成一个动画。

  • The first four, x, y, width, and height are required and define the frame rectangle.

  • The fifth, imageIndex, specifies the index of the source image (defaults to 0)

  • The last two, regX and regY specify the registration point of the frame

frames: [
// x, y, width, height, imageIndex*, regX*, regY*
[64, 0, 96, 64],
[0, 0, 64, 64, 1, 32, 32],
// etc.
];

数组下标 4,5,6 分别是 imageIndex, regX, regY,其中 imageIndex 是指定图片的索引,regX, regY 是指定注册点的位置。

因此,根据上面的定义,我们可以将一张图片分割成多张,然后组合成一个动画。

寻找节点并播放动画

  • 通过 getChildByName 方法可以寻找到节点,然后通过 gotoAndPlay 方法播放动画。
var stage = new createjs.Stage('canvas');
var container = new createjs.Container();
stage.addChild(container);

var spriteSheet = new createjs.SpriteSheet({
images: ['./images/1.png'],
frames: [
// x, y, width, height, imageIndex*, regX*, regY*
[64, 0, 96, 64],
[0, 0, 64, 64, 1, 32, 32],
// etc.
],
animations: {
walk: [0, 9, 'walk', 4],
attack: [10, 20, 'attack', 2],
},
});

var sprite = new createjs.Sprite(spriteSheet, 'walk');
sprite.name = 'sprite';
container.addChild(sprite);

stage.getChildByName('sprite').gotoAndPlay('attack');

需要注意的是,getChildByName 方法只能寻找到子节点,如果要寻找到孙子节点,需要自己实现一个方法。