Canvas: Textures & Sprite animation

Sprites

A sprite sheet is a simple bitmap or block images to a more sophisticated animated image as shown in the example below. Sprites often help in improving the performance of the application in many ways. I2djs provides a set of texture APIs to handle sprites efficiently and easily.

The below example explains the sprite animation in detail:

Layer Creation:

canvasLayer method invoked with ContainerID "#myCanvas". It returns the Canvas2D renderer instance.

let renderer = i2d.canvasLayer('#myCanvas', {}, {});

Texture creation.

Create texture instance using canvasLayer API - createTexture as shown below. In the below example we are creating a texture of size 100 * 100. and the Clip property of the createTexture gives details of the image block on the sprite image. This will help the renderer in extracting the exact pixel block from the sprite.

Clip: { sx: 0, sy: 0, swidth: 108, sheight: 140}

- sx - sprite x start pixel position, sy -sprite y start pixel position, swidth - sprite width pixels, sheight - sprite height pixel.

let textureInstance = renderer_.createTexture({
                attr: {
                    src: "../images/boySprite.png",
                    width: 100,
                    height: 100,
                    clip: {
                        sx: 0,
                        sy: 0,
                        swidth: 108,
                        sheight: 140,
                    },
                    onload: function () {},
                    onerror: function () {}
                },
            });

Image Element creation.

Create an image element with TextureInstance as the source and set the height, width, x, and y for the image element.

var img = renderer_.createEl({
	el: 'image',
	attr: {
		src: textureInstance,
		width: 100,
		height: 100,
		x: 300,
		y: 0
	}
});

The result will be :

Animation:

we need to animate the clip property of the texture instance to create the sprite animations. Move the sx and sy properties of the clip property continuously based on the animation time factor f to create the below animation.

textureInstance.animateTo({
		duration: 1000,
		loop: 6,
		attr: {
			clip: function (f) {
				if (f == 1)
					return { sx: 7 * 108, sy: 0, swidth: 108, sheight: 140 };
				else
					return { sx: parseInt((f * 10) * (8 / 10)) * 108, sy: 0, swidth: 108, sheight: 140 };
			}
		}
	});

Last updated