2017-06-06 82 views
1

在React組件中,如何渲染使用畫布創建的圖像?從React中的canvas context.getImageData渲染ImageData

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 ? 
} 

回答

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

請使用canvas.toDataURLcanvas內容轉換爲data URI,那麼你就可以渲染的img標籤圖像傳送數據URI爲src屬性:

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

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