Skip to content

Commit

Permalink
Add getContext wrapper
Browse files Browse the repository at this point in the history
This wrapper handles the possible null value for `getContext()`. Removing the need to check for it inline. See microsoft/TypeScript#19229 for more information.
  • Loading branch information
imjasonmiller committed Dec 28, 2019
1 parent 65b788d commit 1e6b4ed
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
14 changes: 13 additions & 1 deletion src/__tests__/filtercanvas.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { getCanvasElement, loadImage } from "./../filtercanvas"
import {
getCanvasElement,
getCanvasContext,
loadImage,
} from "./../filtercanvas"

describe("FilterCanvas", () => {
beforeAll(() => (document.body.innerHTML = `<canvas id="canvas"></canvas>`))
Expand All @@ -12,6 +16,14 @@ describe("FilterCanvas", () => {
})
})

describe("getCanvasContext", () => {
it("should return a 2d context", () => {
const result = getCanvasContext(document.createElement("canvas"), "2d")

expect(result).toBeInstanceOf(CanvasRenderingContext2D)
})
})

describe("loadImage", () => {
const originalImageFn = Object.getOwnPropertyDescriptor(
Image.prototype,
Expand Down
19 changes: 17 additions & 2 deletions src/filtercanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,22 @@ export const getCanvasElement = (elem: string): HTMLCanvasElement => {
return canvas
}

export interface CanvasContextMap {
"2d": CanvasRenderingContext2D
webgl: WebGLRenderingContext
webgl2: WebGL2RenderingContext
bitmaprenderer: ImageBitmapRenderingContext
}

export const getCanvasContext = <T extends keyof CanvasContextMap>(
canvas: HTMLCanvasElement,
contextType: T,
): CanvasContextMap[T] => {
const context = canvas.getContext(contextType)
if (!context) throw new Error("could not return drawing context")
return context as CanvasContextMap[T]
}

export const loadImage = (url: string): Promise<HTMLImageElement> =>
new Promise((resolve, reject) => {
const img = new Image()
Expand All @@ -31,7 +47,7 @@ class FilterCanvas {

constructor(elem: string, imgUrl: string) {
this.canvas = getCanvasElement(elem)
this.context = this.canvas.getContext("2d") as CanvasRenderingContext2D
this.context = getCanvasContext(this.canvas, "2d")

this.frames = new FrameCounter(30)

Expand Down Expand Up @@ -104,4 +120,3 @@ class FilterCanvas {
}

export default FilterCanvas

0 comments on commit 1e6b4ed

Please sign in to comment.