[英]Updating <canvas/> with React and setTimeout
我希望以下代碼導致React
<canvas>
包含單詞'foo' <canvas>
並用單詞'bar'更新<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}/>
)
}
})
您可以在CanvasTest中使用“ componentWillReceiveProps”
componentWillReceiveProps(newProps) {
ctx.fillText(newProps.text, 10, 50);
// to re-render
this.forceUpdate();
}
原來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)
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.