PIXI – Drawing Graphics and Creating Textures

 

PIXI JS – Drawing Graphics & Generating Textures

So you know how to create graphics, but you don’t know how to use them as a sprite, or manipulate them, or you would like to know how to draw graphics? Well no problem, with PIXI, drawing graphics has never been easier and you can convert any graphics object into a texture using either Canvas or WebGL renderers.

Haven’t got your PIXI project setup yet? Click here to learn how!

Lets begin by creating a nice looking square.


let graphics: PIXI.Graphics = new PIXI.Graphics();
graphics.beginFill(0xff22aa);
graphics.drawRect(0, 0, 50, 50);
graphics.endFill();

So at this point, you would normally add this graphics object to your container or stage in order to be rendered? Well, lets convert it to a texture so we can use a sprite instead!


...
// this will use the current renderer (WebGL / Canvas) to create a texture
let texture: PIXI.Texture = renderer.generateTexture(graphics);
// however if you wish to force a canvas renderer to generate the texture, you can do this
let texture: PIXI.Texture = graphics.generateCanvasTexture();

Now we can just go ahead and give a sprite, our dashing square as a texture.


...
let superSquare: PIXI.Sprite = new PIXI.Sprite(texture);
stage.addChild(superSquare);

You can of course update the texture at anytime as you normally would. The only caviat to this, is if you draw your texture green, then try to tint it red you will get some gnarly results.

The best thing to do, would be to draw your graphics white, then you can tint as you wish without worrying.

Continue here so see some more advanced graphics than a simple (amazing) square 😉

Twitter

Error code 89: Invalid or expired token.

Stay Updated