KilledByAPixel / LittleJS

LittleJS is a fast HTML5 game engine with many features and no dependencies. 🚂 Choo-Choo!
Other
3.35k stars 172 forks source link

Update types for `drawCanvas2D` #108

Closed snowfrogdev closed 1 month ago

snowfrogdev commented 2 months ago

This is the current function signature in TypeScript:

drawCanvas2D(pos: Vector2, size: Vector2, angle: number, mirror: boolean, drawFunction: Function, screenSpace?: boolean, context?: CanvasRenderingContext2D): void

I'd like to propose changing it to

type CanvasContext = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
function drawCanvas3D<C extends CanvasContext | undefined>(
  pos: Vector2,
  size: Vector2,
  angle: number,
  mirror: boolean,
  drawFunction: C extends undefined
    ? (ctx: CanvasRenderingContext2D) => void
    : (ctx: C) => void,
  screenSpace?: boolean,
  context?: C
): void

This allows for the passing of an offscreen canvas, as well as a regular canvas. It also improves the typing of drawFunction such that ctx will now be correctly typed and inferred based on what is passed to context. If nothing is passed, if defaults to CanvasRenderingContext2D since LJS will use the mainCanvasContext by default.

I'd be happy to make a PR if this is deemed a worthy improvement.

KilledByAPixel commented 1 month ago

Thanks for the suggestion, I made the change to types for all the draw functions, will rebuild soon. I'm not sure how to set the type signature of the draw function using jsdoc though, will take a look at that when i get a chance.

Here is the change...

https://github.com/KilledByAPixel/LittleJS/commit/aa52f6249f8e754b6f6a5f57f1f4c9eee7fde01a