使用React和setTimeout更新<canvas>

时间:2017-07-26 15:36:13

标签: javascript reactjs canvas

我希望以下代码能够导致React

  • 向页面呈现画布标记,其中<canvas>包含单词&#39; foo&#39;
  • 一秒后将道具改为&#39; bar&#39;
  • 使用&#39; bar&#39;更新<canvas>。并使用&#39; bar&#39;
  • 更新<span>

<span>更新,但不是<canvas>

import React from 'react'

var CanvasTest = React.createClass({

  componentDidMount() {
    this.animate(this.props.text)
  },

  animate(str) {
    var c = document.getElementById('canvas')
    var ctx = c.getContext('2d')
    ctx.clearRect(0,0,10,50)
    ctx.fillText(str, 10, 50)
  },

  render() {
    return (
      <div>
        <span>{this.props.text}</span>
        <canvas id="canvas" width="100" height="100"></canvas>
      </div>
    )
  }

})

export default React.createClass({

  getInitialState() {
    return {
      str: 'foo'
    }
  },

  componentDidMount() {

    setTimeout(() => {
      this.setState({ str: 'bar' })
    }, 1000)

  },

  render() {
    return (
      <CanvasTest text={this.state.str}/>
    )
  }

})

2 个答案:

答案 0 :(得分:0)

你可以使用&#34; componentWillReceiveProps&#34;在CanvasTest内部

componentWillReceiveProps(newProps) {
    ctx.fillText(newProps.text, 10, 50);

    // to re-render
    this.forceUpdate();
}

答案 1 :(得分:0)

结果clearRect只清除了canvas的一小部分,请参阅下面的参数:

animate(str) {
  var c = document.getElementById('canvas')
  var ctx = c.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.fillText(str, 10, 50)
},