从React中的canvas context.getImageData渲染ImageData

时间:2017-06-06 07:07:00

标签: javascript reactjs canvas

在React组件中,如何渲染使用画布创建的图像?

componentWillMount () {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  canvas.width = 256
  canvas.height = 256
  // omitted canvas painting code
  const image = context.getImageData(0, 0, canvas.width, canvas.height)
  this.setState({image})
}

render() {
  return ?
}   

2 个答案:

答案 0 :(得分:1)

我不确定你可以直接在render方法中渲染它。但是如果你使用componentDidMount / componentDidUpdate挂钩,你可以绘制它。如果你用状态设置它。

class Hi extends React.Component {
  state = {};
  componentWillMount () {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = 256
    canvas.height = 256
    context.rect(20,20,150,100);
    context.stroke();
    const image = context.getImageData(0, 0, canvas.width, canvas.height)
    this.setState({image})
  }
  componentDidMount() {
    const context = this.refs.canvas.getContext('2d');
    context.putImageData(this.state.image, 0, 0);
  }
  render() {
    return <canvas ref="canvas" />
  }
}

ReactDOM.render(<Hi />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

答案 1 :(得分:1)

请使用valgrind将您的canvas内容转换为data URI,然后您可以使用img标记呈现图片,并将数据URI作为src属性传递:

<img src={this.state.dataURI} />

&#13;
&#13;
class Example extends React.Component {
  state = {}

  componentWillMount () {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = 256
    canvas.height = 256
    
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 70;

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();

    const dataURI = canvas.toDataURL()
    this.setState({dataURI})
  }

  render() {
    return <img src={this.state.dataURI} />
  }
}

ReactDOM.render(<Example />, document.body)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;