Working with ReactJS and HTML5 Canvas

Working with ReactJS and HTML5 Canvas

本文关键字:HTML5 Canvas and ReactJS with Working      更新时间:2023-09-26

我有一个根组件渲染<Particle />组件和<Particle />组件渲染功能是:

render: function(){
        var data = this.props.data,
            canvas = document.createElement('canvas'),
            context;
        canvas.style.position = 'absolute';
        canvas.style.top = data.y + 'px';
        canvas.style.left = data.x + 'px';
        context = canvas.getContext('2d');
        context.drawImage(data.img, data.x, data.y, data.tileSize, data.tileSize, 0, 0, data.tileSize, data.tileSize);
        return canvas;
    }

返回以下错误:

Uncaught Error: Invariant Violation: Particle.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

我看了看Flipboard的react-canvas,但我找不到任何与我的情况相似的好例子。

您应该只返回一个带有对它的引用的单个canvas元素。这个元素与DOM节点不同;React使用JSX将其转换为React组件:

render: function() {
    return <canvas ref="canvas" />
}

然后在生命周期方法中修改它:

componentWillReceiveProps: function() {
    var canvas = React.findDOMNode(this.refs.canvas);
    canvas.style.position = 'absolute';
    // etc ...
}

你也可以在render中设置一些内联样式属性:

render: function() {
    var styles = {
        position: 'absolute',
        top: this.props.data.y,
        left: this.props.data.x
    }
    return <canvas ref="canvas" style={styles} />
}

…但是context/drawimage最好放在一个生命周期方法中,因为你需要访问dom节点。