利用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 (
      <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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,761评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • 不知道从什么时候开始,竟然爱上了坐车,以前晕车晕到绝望的自己,简直不敢置信,可能人都是这样,现在你觉得讨厌,觉得难...
    丸子倩阅读 161评论 0 1
  • 那一年,我和你一起坐在教室里,有说有笑,我们曾哭过,笑过。感谢你给我鼓励,让我找回了自己,让我勇敢。终于到了离开的...
    默然千里阅读 187评论 0 0