So for todays post on the html5 game framework known as phaser ce, the community edition of phaser ce. I will be writing about a way to go about making sprites form 2d canvas elements. This means making a sprite using the html 5 2d drawing context via a canvas element that has been made before hand elsewhere, or directly drawing to a new one. In any case the canvas can be used to make an instance of bitmap data that can then be used as a texture for a sprite, rather than an external image. I will not be getting into how to go about spritesheets for now, as I think that should be a whole other post.
For a basic working example of this, the process is to start out by making a canvas element, or using the canvas element that is in an instance of bitmapData, and then draw something to it like always when doing something with canvas. I can not just pass a canvas element as the texture for a sprite, but I can pass an instance of bitmap data. That being said I must then create an instance of bitmap data, which will have a canvas as one of its properties. I can either directly draw to that canvas, or draw another canvas to that canvas with drawImage. Once I have my bitmap data I can then use that as the texture for a sprite.
In any case doing this will often involve making an instance of the phaser bitmap data class. This class will have a canvas as one of its properties, and as such if I am not doing anything that involves a canvas element that exists before hand, I can just draw to the context of that canvas.
If I want to cache the bitmap data I would want to use game.add.bitMapdata, and set a boolen with that true rather than directly using the constructor like I am in this example.
In order to pull this off I can just draw to the bitmap data canvas with the other canvas.
In this example I am creating the canvas in the same body of code. However I could create a function where something like this would be pulled away into. In a real project I might have some kind of module that returns a canvas and I need to fine a way to make a sprite from it, in such a case a function that does that would be helpful.
So If I am in a situation in which I want to make a whole bunch of sprites from one bitmap image that is made by drawing to is canvas. Then I would do something similar to the example in which I am drawing directly to a canvas like before. However this time I will want to cache it to phasers cache, and then grab at it when I need to when creating a new sprite in my states update method.
So then this way I can make a whole bunch of sprites from just one bitmapData instance that is cached.