2017-06-22 82 views
1

如何將圖片上傳到React畫布的全寬/高度?例如:如何在React中的畫布上加載圖像?

class PlanPage extends Component { 
 
    constructor(props) { 
 
    super(props); 
 
    } 
 

 
    componentWillMount() { 
 
    this.setState({ 
 
     canvasA: { 
 
     canvasWidth: 800, 
 
     canvasHeight: 600 
 
     } 
 
    }) 
 
    } 
 

 
    componentDidMount() { 
 
    this.props.getDataMap(); //return object which has the fields e.g. id,... and field URL which specifies where image is 
 
    const { canvasWidth, canvasHeight } = this.state.canvasA; 
 
    this.canvasA.width = canvasWidth; 
 
    this.canvasA.height = canvasHeight; 
 
    } 
 
...... 
 
<canvas 
 
    ref={canvasA => this.canvasA = canvasA} /> //canvas
<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>

會知道的任何幫助。

回答

2

你可以嘗試這樣的事情

componentDidMount() { 
    const context = this.canvasA.getContext('2d'); 

    const image = new Image(); 
    image.src = "whereever-you-image-url-live.jpg"; 
    image.onload =() => { 
    context.drawImage(image, 0, 0, this.canvasA.width, this.canvasA.height); 
    }; 
} 
+0

謝謝@Nick緯。好的實現。 – vvn92