Graphics are special object that abstract something that can be drawn to the screen. Examples include circles, polygons, and sprites.
Excalibur ex.Graphic
s break into 2 main categories, Sprite based and Raster based. That is to say Raster and non-Raster graphics.
All Graphics have a bunch of useful feature that work for ALL types of graphics
clone(): Graphic
width: number
height: number
flipHorizontal: boolean
flipVertical: boolean
rotation: number
opacity: number
scale: Vector
origin: Vector
Rasters are a type of ex.Graphic
built by constructing a bitmap (using CanvasRenderingContext2D) in memory which is then sent to the drawing context. This allows the use of features available to developers in the 2D canvas to produce Graphics for Excalibur. It's important to share or limit the number of Raster graphics due to their memory footprint in the browser.
Rasters are only rendered when they need to be, if no properties change on them, they are not recalculated. Rasters can be forced to be re-draw by calling .flagDirty()
.
See these useful raster implemenations
A custom raster can be built implementing the execute
function, this is in fact how the Canvas is implemented.
export class MyRaster extends ex.Raster {
constructor() {
super()
}
execute(ctx: CanvasRenderingContext2D): void {
// my custom raster
ctx.fillStyle = 'blue'
ctx.fillRect(0, 0, 20, 20)
}
}
ex.Raster
properties and methods
abstract execute(ctx: CanvasRenderingContext2D): void
rasterize(): void
execute()
implementation in the processPolygon creates a rastered polygon graphic given a set of points
const triangle = new ex.Polygon({
points: [ex.vec(10 * 5, 0), ex.vec(0, 20 * 5), ex.vec(20 * 5, 20 * 5)],
color: ex.Color.Yellow,
})
Circle creates a rastered circle graphic given a raidus
const circle = new ex.Circle({
radius: 10,
color: ex.Color.Red,
})
Rectangle creates a rastered rectange graphic given a width and height
const rect = new ex.Rectangle({
width: 100,
height: 100,
color: ex.Color.Green,
})
The canvas is a special type of raster graphic that acts like a shim between direct CanvasRenderingContext2D drawing and the ExcaliburGraphicsContext
This type of raster is re-rendered every time the graphic is drawn, thus it should be used sparingly due to this inefficiency.
const canvas = new Canvas({
draw: (ctx: CanvasRenderingContext2D) => {
...
}
});