简体   繁体   中英

Upload image to redux and show in React-Konva

I have try to upload image to Redux and show in of React-Konva in many ways. But it isn't work. Both in base64 and blob. But in normal situation like using component's state to keep data(base64) it's work. I don't know why. In my component just have button for upload and React-Konva Component for show image

this is error from base64 store in redux and show to Image Tag

class UploadButton extends Component{
  constructor(props){
    ...
    this.handleUpload = this.handleUpload.bind(this);
  }

  handleUpload({target}){
    const reader = new FileReader();
    const file = target.files[0];
    reader.onloadend = () => {
      this.props.dispatch({
        type: 'UPLOAD_IMAGE',
        image: reader.result, 
      });
    };
    reader.readAsDataURL(file);
  }

  render(){
    return(
      <div>
        <input 
          value="Upload" 
          type="button" 
          onClick={ () => { this.uploadInput.click() } } 
        />
        <input 
          id="inputUpload"
          ref={ (ref) => { this.uploadInput = ref } }
          type="file" 
          style={ { display: 'none' } } 
          onChange = { (event) => { this.handleUpload(event) }}
        />
      </div>
    );

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { Stage, Layer, Image } from 'react-konva';

class ShowImage extends Component {
  constructor(props){
    super(props);
    this.props = props;

    this.state = {
      image : null,
    }
  }


  render(){
    return (
      <Stage
        width={ 500 }
        height={ 500 }
      >
        <Layer>
         <Image image={ this.props.image} ></Image>
        </Layer>
      </Stage>
    );
  }
}

const mapStateToProps = ( state ) => ({
  image : state.image,
});

export default connect(mapStateToProps)(ShowImage);

To use the image in react-konva you have to create a native instance of window.Image .

class VaderImage extends React.Component {
  state = {
    image: new window.Image()
  };
  componentDidMount() {
    this.state.image.src = this.props.image;
    this.state.image.onload = () => {
      // need to update layer manually
      this.imageNode.getLayer().batchDraw();
    };
  }

  render() {
    return (
      <Image
        image={this.state.image}
        y={250}
        ref={node => {
          this.imageNode = node;
        }}
      />
    );
  }
}

https://konvajs.github.io/docs/react/Images.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM