美文网首页
利用WebView组件来渲染Canvas

利用WebView组件来渲染Canvas

作者: Axiba | 来源:发表于2016-01-13 21:22 被阅读2134次

    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);
    
    

    相关文章

      网友评论

          本文标题:利用WebView组件来渲染Canvas

          本文链接:https://www.haomeiwen.com/subject/xaickttx.html