Skip to content
This repository was archived by the owner on Aug 15, 2019. It is now read-only.

Commit fd49f54

Browse files
authored
Make sure tf.fromPixels() gets called after the DOM is ready (#1064)
BUG Since a newer version of Chrome, you have to create the canvas element when the DOM is ready in order to get a 2d rendering context. This PR postpones the creation of a fromPixelsCanvas element until the user calls fromPixels(). This makes the webcam-transfer-learning example work. Fixes tensorflow/tfjs#313
1 parent 39a02f5 commit fd49f54

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/kernels/backend_webgl.ts

+20-8
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ export interface WebGLTimingInfo extends TimingInfo {
8888
export class MathBackendWebGL implements KernelBackend {
8989
private texData = new WeakMap<DataId, TextureData>();
9090
private canvas: HTMLCanvasElement;
91+
private fromPixelsCanvas: HTMLCanvasElement;
9192

9293
private programTimersStack: TimerNode[];
9394
private activeTimers: TimerNode[];
@@ -119,16 +120,24 @@ export class MathBackendWebGL implements KernelBackend {
119120
const outShape = [pixels.height, pixels.width, numChannels];
120121

121122
if (pixels instanceof HTMLVideoElement) {
122-
if (this.canvas == null) {
123-
throw new Error(
124-
'Can\'t read pixels from HTMLImageElement outside ' +
125-
'the browser.');
123+
if (this.fromPixelsCanvas == null) {
124+
if (typeof document === 'undefined') {
125+
throw new Error(
126+
'Can\'t read pixels from HTMLImageElement outside the browser.');
127+
}
128+
if (document.readyState !== 'complete') {
129+
throw new Error(
130+
'The DOM is not ready yet. Please call tf.fromPixels() ' +
131+
'once the DOM is ready. One way to do that is to add an event ' +
132+
'listener for `DOMContentLoaded` on the document object');
133+
}
134+
this.fromPixelsCanvas = document.createElement('canvas');
126135
}
127-
this.canvas.width = pixels.width;
128-
this.canvas.height = pixels.height;
129-
this.canvas.getContext('2d').drawImage(
136+
this.fromPixelsCanvas.width = pixels.width;
137+
this.fromPixelsCanvas.height = pixels.height;
138+
this.fromPixelsCanvas.getContext('2d').drawImage(
130139
pixels, 0, 0, pixels.width, pixels.height);
131-
pixels = this.canvas;
140+
pixels = this.fromPixelsCanvas;
132141
}
133142
const tempPixelArray = Tensor.make(texShape, {}, 'int32');
134143

@@ -1017,6 +1026,9 @@ export class MathBackendWebGL implements KernelBackend {
10171026
}
10181027
this.textureManager.dispose();
10191028
this.canvas.remove();
1029+
if (this.fromPixelsCanvas != null) {
1030+
this.fromPixelsCanvas.remove();
1031+
}
10201032
if (this.gpgpuCreatedLocally) {
10211033
this.gpgpu.dispose();
10221034
}

0 commit comments

Comments
 (0)