在尝试动态更改图像时,图像不显示

时间:2017-01-20 09:00:45

标签: reactjs html5-canvas

我想动态更改图像,静态图像工作正常。在动态中,当我点击选择文件时,显示的是图片网址,但图片没有显示。这是我的代码。

       {
      (this.state.imageChange==true)?(
        <canvas  id="Canvas" ref="myCanvas" width={300} height={300} />

    ):(
      <div style={{marginTop:15, marginBottom:15, marginLeft:15}}>
      </div>
    )
  }
  <input type="file" id="fileupload" name="files[]" onChange={this.fileChange.bind(this)}/>
  <input type="button" id="upload" value="Save"/>

我使用了画布的概念。

const canvas =this.refs.myCanvas;
const context = canvas.getContext('2d');
context.fillRect(0,0, 100, 100);
var mapSprite = new Image();
mapSprite.src = this.state.pic;  

这是我的fileChange方法

fileChange(){
 this.setState({imageChange:true});
 var pic=document.getElementById("fileupload").files[0].name;
 this.setState({pic:pic},()=>{
    console.log("picture:"+this.state.pic);
 });
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您必须为上传的文件创建一个网址。

function handleChange(files) {
   const pic = URL.createObjectURL(files[0]);
   console.log(pic);
   this.setState({pic, imageChange: true});
}
  

另一种选择是使用一些反应库,如react-dropzone,然后你不必做所有这些。

相关问题