Skip to content

Commit

Permalink
memoize canvas context without react
Browse files Browse the repository at this point in the history
  • Loading branch information
kiritnarain committed Mar 29, 2022
1 parent 64e21a3 commit 6a3312a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@spotxyz/virtual-background",
"version": "0.1.0-custom5",
"version": "0.1.0-custom6",
"description": "Demo on adding virtual background to a live video stream in the browser",
"homepage": "https://github.com/spotxyz/virtual-background",
"repository": "https://github.com/spotxyz/virtual-background.git",
Expand Down
14 changes: 10 additions & 4 deletions src/pipelines/webgl2/webgl2Pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,19 @@ import { buildJointBilateralFilterStage } from './jointBilateralFilterStage'
import { buildLoadSegmentationStage } from './loadSegmentationStage'
import { buildResizingStage } from './resizingStage'
import { buildSoftmaxStage } from './softmaxStage'
import { useMemo } from "react";

export function buildWebGL2Pipeline(
let prevCanvas: HTMLCanvasElement;
let gl: WebGL2RenderingContext;

export const buildWebGL2Pipeline = (
sourcePlayback: SourcePlayback,
backgroundImage: HTMLImageElement | null,
backgroundConfig: BackgroundConfig,
segmentationConfig: SegmentationConfig,
canvas: HTMLCanvasElement,
tflite: TFLite,
addFrameEvent: () => void
) {
) => {
const vertexShaderSource = glsl`#version 300 es
in vec2 a_position;
Expand All @@ -48,7 +50,11 @@ export function buildWebGL2Pipeline(
segmentationConfig.inputResolution
]

const gl = useMemo(() => canvas.getContext('webgl2')!, [canvas]);
// Prevent unnecessary canvas contexts from being created
if(canvas !== prevCanvas){
gl = canvas.getContext('webgl2')!;
}
prevCanvas = canvas;

const vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexShaderSource)

Expand Down

0 comments on commit 6a3312a

Please sign in to comment.