-
Notifications
You must be signed in to change notification settings - Fork 8
/
game-up-camera-1.0.0.js
81 lines (60 loc) · 2.5 KB
/
game-up-camera-1.0.0.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2016 BrainPOP
// Released under MIT License,
// see https://raw.githubusercontent.com/phetsims/sherpa/main/licenses/game-up-camera-1.0.0.js.txt
/**
* Responds to requests from BrainPOP/Game Up/SnapThought for return images from a PhET simulation.
* @author BrainPOP
* @author Vin Rowe
* @author Sam Reid (PhET Interactive Simulations)
*/
const logging = window.phet.chipper.queryParameters.gameUpLogging;
const isGameUp = window.phet.chipper.queryParameters.gameUp;
const isGameUpTestHarness = window.phet.chipper.queryParameters.gameUpTestHarness;
const log = text => logging && console.log( text );
// Only enable if a query parameter is set
if ( isGameUp ) {
log( 'Enabled Game Up Camera' );
const suffix = '.brainpop.com';
// haven't received word from the parent that captureReady succeeded
let gameUpCaptureReady = false;
// Stop checking after 10 times in case we somehow missed the GameUpCaptureReady message
let numberOfChecks = 0;
const checkInitialization = () => {
// haven't received word from the parent that captureReady succeeded
if ( !gameUpCaptureReady && numberOfChecks < 10 ) {
parent.postMessage( 'captureReady', '*' );
numberOfChecks++;
log( 'Posted captureReady, number of checks: ' + numberOfChecks );
setTimeout( checkInitialization, 1000 );//try again in a second
}
};
const receiver = event => {
if ( event.origin.indexOf( suffix, event.origin.length - suffix.length ) !== -1 || isGameUpTestHarness ) {
if ( event.data === 'captureImage' ) {
const dataURL = window.phet.joist.ScreenshotGenerator.generateScreenshot( window.phet.joist.sim, 'image/jpeg' );
sendImage( dataURL, event.origin, event.source );
log( 'Sent image' );
}
else if ( event.data === 'GameUpCaptureReady' ) {
log( 'GameUpCaptureReady' );
// TODO: post captureReady from here
//captureReady succeeded
gameUpCaptureReady = true;
}
}
};
const sendImage = ( imageString, origin, source ) => {
//capture.js already appends this, so we end up with two
imageString = imageString.replace( 'data:image/jpeg;base64,', '' );
//send it back
source.postMessage( imageString, origin );
};
if ( window.addEventListener ) {
window.addEventListener( 'message', receiver, false );
}
else if ( window.attachEvent ) {
window.attachEvent( 'onmessage', receiver );
}
// Call captureReady, function will recall itself until gameUpCaptureReady
checkInitialization();
}