1010 Platform
1111} = require ( 'react-native' ) ;
1212
13+ function getRenderHTML ( context , render , generator ) {
14+ return `
15+ <style>
16+ *{margin:0;padding:0;}canvas{transform:translateZ(0);}
17+ </style>
18+ <canvas></canvas>
19+ <script>
20+ var canvas = document.querySelector('canvas');
21+ (${ render } ).call(${ context } , canvas);
22+ (${ generator } ).call('', ${ context } , canvas);
23+ </script>"
24+ ` ;
25+ }
26+
27+ function generateImage ( context , canvas ) {
28+ if ( window . postMessage . length !== 1 ) {
29+ setTimeout ( function ( ) {
30+ ( generateImage ) . call ( this , context , canvas ) ;
31+ } , 100 ) ;
32+ } else {
33+ const image = document . createElement ( 'canvas' ) ;
34+ const imageContext = image . getContext ( '2d' ) ;
35+ image . width = context . size ;
36+ image . height = context . size ;
37+ imageContext . fillStyle = context . bgColor ;
38+ imageContext . fillRect ( 0 , 0 , context . size , context . size ) ;
39+ imageContext . drawImage ( canvas , 0 , 0 ) ;
40+ window . postMessage ( image . toDataURL ( ) ) ;
41+ }
42+ }
43+
1344var Canvas = createReactClass ( {
1445 propTypes : {
1546 style : PropTypes . object ,
@@ -19,16 +50,23 @@ var Canvas = createReactClass({
1950 onLoadEnd : PropTypes . func ,
2051 } ,
2152
53+ getImage : function ( event ) {
54+ if ( this . props . generateImage ) {
55+ this . props . generateImage ( event . nativeEvent . data ) ;
56+ }
57+ } ,
58+
2259 render ( ) {
2360 var contextString = JSON . stringify ( this . props . context ) ;
2461 var renderString = this . props . render . toString ( ) ;
62+ var generate = generateImage . toString ( ) ;
2563 return (
2664 < View style = { this . props . style } >
2765 < WebView
2866 automaticallyAdjustContentInsets = { false }
2967 scalesPageToFit = { Platform . OS === 'android' }
3068 contentInset = { { top : 0 , right : 0 , bottom : 0 , left : 0 } }
31- source = { { html : "<style>*{margin:0;padding:0;}canvas{transform:translateZ(0);}</style><canvas></canvas><script>var canvas = document.querySelector('canvas');(" + renderString + ").call(" + contextString + ", canvas);</script>" } }
69+ source = { { html : getRenderHTML ( contextString , renderString , generate ) } }
3270 opaque = { false }
3371 underlayColor = { 'transparent' }
3472 style = { this . props . style }
@@ -37,6 +75,7 @@ var Canvas = createReactClass({
3775 onLoad = { this . props . onLoad }
3876 onLoadEnd = { this . props . onLoadEnd }
3977 originWhitelist = { [ '*' ] }
78+ onMessage = { this . getImage }
4079 />
4180 </ View >
4281 ) ;
0 commit comments