利用WebView组件来渲染Canvas

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

  • 上下文对象:Context,通过React-Native传入WebView组件
  • 渲染方法:renderCanvas

组件模块的引入

  • 需要相对路径引入

组件代码:

'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 (
      
          *{margin:0;padding:0;} canvas{position:absolute;transform:translateZ(0);}"}
          opaque={false}
          underlayColor={'transparent'}
          style={this.props.style}/>
      
    );
  }
});


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 (
      
          {
            
              
          
        }
      
    );
  },
});
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);

你可能感兴趣的:(利用WebView组件来渲染Canvas)