Skip to content

Commit

Permalink
fix(RTTR): implement HTMLCanvasElement.getContext
Browse files Browse the repository at this point in the history
  • Loading branch information
CodyJasonBennett committed Jun 28, 2023
1 parent b1bdccf commit 58638a0
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions packages/test-renderer/src/createTestCanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,31 @@ import { WebGL2RenderingContext } from './WebGL2RenderingContext'
import type { CreateCanvasParameters } from './types/internal'

export const createCanvas = ({ beforeReturn, width = 1280, height = 800 }: CreateCanvasParameters = {}) => {
const canvas =
typeof document !== 'undefined' && typeof document.createElement === 'function'
? document.createElement('canvas')
: ({
style: {},
addEventListener: (() => {}) as any,
removeEventListener: (() => {}) as any,
clientWidth: width,
clientHeight: height,
getContext: (() => new WebGL2RenderingContext(canvas)) as any,
} as HTMLCanvasElement)
let canvas: HTMLCanvasElement

if (typeof document !== 'undefined' && typeof document.createElement === 'function') {
canvas = document.createElement('canvas')
} else {
canvas = {
style: {},
addEventListener: (() => {}) as any,
removeEventListener: (() => {}) as any,
clientWidth: width,
clientHeight: height,
getContext: (() => new WebGL2RenderingContext(canvas)) as any,
} as HTMLCanvasElement
}
canvas.width = width
canvas.height = height

if (globalThis.HTMLCanvasElement) {
const getContext = HTMLCanvasElement.prototype.getContext
HTMLCanvasElement.prototype.getContext = function (id: string) {
if (id.startsWith('webgl')) return new WebGL2RenderingContext(this)
return getContext.apply(this, arguments as any)
} as any
}

beforeReturn?.(canvas)

class WebGLRenderingContext extends WebGL2RenderingContext {}
Expand Down

0 comments on commit 58638a0

Please sign in to comment.