Function Graphics

A Graphics object is a way to draw primitive shapes to your game. Primitives include forms of geometry, such as Rectangles, Circles, and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will be empty.

To draw to it you must first specify a line style or fill style (or both), draw shapes using paths, and finally fill or stroke them. For example:

graphics.lineStyle(5, 0xFF00FF, 1.0);
graphics.beginPath();
graphics.moveTo(100, 100);
graphics.lineTo(200, 200);
graphics.closePath();
graphics.strokePath();

There are also many helpful methods that draw and fill/stroke common shapes for you.

graphics.lineStyle(5, 0xFF00FF, 1.0);
graphics.fillStyle(0xFFFFFF, 1.0);
graphics.fillRect(50, 50, 400, 200);
graphics.strokeRect(50, 50, 400, 200);

When a Graphics object is rendered it will render differently based on if the game is running under Canvas or WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes.

If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help performance by calling Phaser.GameObjects.Graphics#generateTexture. This will 'bake' the Graphics object into a Texture, and return it. You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then you should avoid doing this, as it will constantly generate new textures, which will consume memory.

As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful in their complexity and quantity of them in your game.

Properties

contextTypes?: ValidationMap<any>

Lets you specify which legacy context is consumed by this component.

defaultProps?: Partial<GameObjectProps<Graphics>>

Used to define default values for the props accepted by the component.

type Props = { name?: string }

const MyComponent: FC<Props> = (props) => {
return <div>{props.name}</div>
}

MyComponent.defaultProps = {
name: 'John Doe'
}
displayName?: string

Used in debugging messages. You might want to set it explicitly if you want to display a different name for debugging purposes.


const MyComponent: FC = () => {
return <div>Hello!</div>
}

MyComponent.displayName = 'MyAwesomeComponent'
propTypes?: WeakValidationMap<GameObjectProps<Graphics>>

Used to declare the types of the props accepted by the component. These types will be checked during rendering and in development only.

We recommend using TypeScript instead of checking prop types at runtime.