利用WebView组件来渲染Canvas

2016-01-13  本文已影响2134人  Axiba

Canvas组件这里使用到了两个属性:

组件模块的引入

组件代码:

'use strict'

var React = require('react-native');
var {
  WebView,
  View,
} = React;

//画布组件
var Canvas = React.createClass({
  propTypes: {
    context: React.PropTypes.object,
    render: React.PropTypes.func.isRequired,
  },
  render() {
    var contextString = JSON.stringify(this.props.context);
    var renderString = this.props.render.toString();
    return (
      <View>
        <WebView automaticallyAdjustContentInsets={false}
          html={"<style>  *{margin:0;padding:0;} canvas{position:absolute;transform:translateZ(0);}</style><canvas></canvas><script>var canvas = document.querySelector('canvas');(" + renderString + ").call(" + contextString + ",canvas);</script>"}
          opaque={false}
          underlayColor={'transparent'}
          style={this.props.style}/>
      </View>
    );
  }
});


module.exports = Canvas;

index.io.js 文件

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var Canvas = require('./components/Canvas');
//增加NavigatorIOS
var {
  AppRegistry,
  StyleSheet,
  Text,
  View
} = React;
var MainClass = React.createClass({

  render: function() {
    var context = {msg : "it's write by canvas!"};
    return (
      <View  style= {styles.container}>
          {
            <View>
              <Canvas context={context}
                render={renderCanvas}
                style={{height: 300,width:300}}></Canvas>
          </View>
        }
      </View>
    );
  },
});
function renderCanvas(canvas) {
  var message = this.msg;
  var ctx = canvas.getContext('2d'),
      colors = ['#f35d4f','#f36849','#c0d988','#6ddaf1','#f1e85b'];

  canvas.width = 500;
  canvas.height = 500;
  canvas.style.left = (window.innerWidth - 200)/2+'px';

  if(window.innerHeight>200)
  canvas.style.top = (window.innerHeight - 200)/2+'px';
  function draw() {
    ctx.font = '20px Georiga';
    ctx.fillText(message, 10 ,50);
  }
  draw();
};
/*布局样式*/
var styles = StyleSheet.create({
  container: {
    flex: 1,
    // justifyContent: 'center',
    // alignItems: 'center',
    marginTop:74,
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('AwesonProject', () => MainClass);

上一篇 下一篇

猜你喜欢

热点阅读